【问题标题】:Select one div after another css selectors [closed]在另一个 CSS 选择器之后选择一个 div [关闭]
【发布时间】:2023-04-07 18:19:02
【问题描述】:

我一直在尝试这样做,感觉应该相当简单:

<div id = "container">
  <div id = "item1" class = "item"> </div>
  <div id = "item2" class = "item"> </div>
  <div id = "item3" class = "item"> </div>
</div>

如何逐个选择每个项目并为每个项目分配不同的background(不使用ids)?

我想要达到的目标:

#item1 {
  background: red;
}

#item2 {
  background: blue;
}

#item3 {
  background: yellow;
}
<div id="container">
  <div id="item1" class="item"> </div>
  <div id="item2" class="item"> </div>
  <div id="item3" class="item"> </div>
</div>

但是有没有办法一个一个地选择#container div 中的每个元素,而不管它的id 值是多少?通过执行以下操作:

.container:nth-child(1){ /*select first child of .conainter (#item1) ?*/
background: red;
}

或

.item:nth-of-type(2){ /*select second element of type .item (#item2) */
background: blue;
}

【问题讨论】:

  • 我也想看看你认为应该先做什么。此外,仅凭此描述不足以了解您要完成的工作。这是重复模式吗?还是每个人都有独特的背景?如果您要选择后者,为什么不直接使用 ID?如果您的孩子多于背景会怎样?
  • @CoryCoolguy 我添加了更多信息并说明了我所说的 nth-child 和 nth-of-type 的意思
  • 在回复您的编辑时,不,您没有正确执行 CSS。要使用第 n 个类型,您必须指定内部值。将第 n 种类型添加到容器中不会起作用,因为您基本上说我希望第二个或第三个容器是红色的等等。看看下面的答案,因为它们提供了 3 个正确的使用方法。
  • nth-of-type vs nth-child的可能重复

标签: css css-selectors


【解决方案1】:

如果您尝试仅使用 CSS:

.item:nth-of-type(1) { background: #fff}
.item:nth-of-type(2) { background: #000}
.item:nth-of-type(3) { background: #abc}

如果你想在事后使用 JS 和/或 jQuery 来获取这些:

jQuery(".item").each(function(i, el) {
   if(i == 0) {
      el.style.backgroundColor = "black";
   } else {
      el.style.backgroundColor = "red";
   }
})

i 这里将是您的.item 元素的索引,因此您可以通过该索引定位您需要的元素(因此是条件)

另外注意,如果你想看到背景颜色的变化,你需要在.item元素上设置一个高度或者添加一些内容。默认高度为0

【讨论】:

  • 不是我@adr5240
  • 我会给你一个 1 分,因为你的答案比我的好 :)
  • 不用担心@user3131132,谢谢你们俩。您介意将此标记为可见性的答案吗?
【解决方案2】:

在 CSS 和 JS 中有几种方法可以实现这一点。下面是我通常在客户网站上使用的变体,以实现您试图实现的这种背景变体:

#container div {width: 200px; height: 200px;}
#container div:first-child {background-color: red;}
#container div:nth-child(2) {background-color: green;}
#container div:last-child {background-color: blue;}

我在#container 中的第一个和最后一个元素上使用第一个子元素和最后一个子元素,然后对于中间的元素,我只是告诉浏览器在#container 中找到第二个 div。

这是我的 HTML,所以我的解释和 CSS 是有意义的:

<div id = "container">
 <div>ITS RED! </div>
 <div>ITS GREEN! </div>
 <div>ITS BLUE! </div>
</div>

在 jsfiddle 环境中随意编辑和玩弄我的代码:https://jsfiddle.net/x9eouw7z/

【讨论】:

  • 我喜欢这个答案。这可能不是他们想要的答案,但它根据提问者的参数回答了问题。
【解决方案3】:

对于静态页面,您可以像这样使用:nth-child() 选择器:

https://jsfiddle.net/DIRTY_SMITH/6brcg9p7/3/

.item:nth-child(1) {
  background: blue;
}
.item:nth-child(2) {
  background: red;
}
.item:nth-child(3) {
  background: green;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 2011-04-14
    • 2011-05-02
    • 2016-04-17
    • 2022-01-07
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多