在另一个CSS选择器之后选择一个div

时间:2019-06-21 15:53:41

标签: css css-selectors

一段时间以来,我一直在尝试这样做,并且感觉应该很简单:

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

如何才能依次选择每个项目并为每个项目分配一个不同的background(不使用id s)?

我要实现的目标:

#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;
}

3 个答案:

答案 0 :(得分:2)

如果您仅尝试使用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

答案 1 :(得分:0)

有几种方法可以在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环境中{@ {3}}

随意编辑和使用我的代码

答案 2 :(得分:0)

对于静态页面,您可以使用: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;
}
相关问题