如何使用纯CSS(无JS)选择每隔一个div类元素?

50

我知道如何使用JavaScript和PHP来做到这一点,但我正在尝试学习如何/是否可以仅使用CSS来实现。

我有一个容器,其中包含许多项。 每个项目都有一张图片,在下面是一个包含描述的

。 我希望每隔一个项目的背景与其他项目不同。

是否可能仅使用CSS实现这一点? 如果可以,怎么做? 我一直在尝试使用选择器。

.item:nth-child(odd){background-color:red}
.item .description:nth-of-type(odd){background-color:orange;}

我似乎无法理解它。欢迎任何建议、评论或意见。
下面是一些简化的示例代码,演示了我的情况。

<style>
#container{width:100% height:100%;}
.item {float:left; width:250px; height:700px;}
.item img {width:250px; height:250px; float:left;}
.description {width:250px; height:450px; float:left; background-color:blue;}
.description:nth-of-type(even){background-color:red;}      // <- Here's the line!!
</style>

<html>
 <body>
  <div id="container">
   <div class="item">       //item 1
    <img src="image.jpg"/>
    <div class="description"> //This (and every odd number) I want to be blue 
     <h1>Title</h1>
     <h2>Sub Title</h2>
     <p>Lorem Ipsum dolor sit for Adun!</p>
     <a href="#">::LEARN MORE::</a>
    </div>
   </div>
   <div class="item">      //item 2 and so on...
    <img src="image.jpg"/>
    <div class="description"> //and this (and every even number, red)
     <h1>Title</h1>
     <h2>Sub Title</h2>
     <p>Lorem Ipsum dolor sit for Adun!</p>
     <a href="#">::LEARN MORE::</a>
    </div>
   </div>
  </div>
 <body>
</html>
4个回答

75

你希望在.item上使用nth-child()

.item:nth-child(odd) .description {
    background-color: red;
}

演示:jsFiddle


2
太棒了的猫咪,哈哈。谢谢! :) - Jaime
5
无法通过类名选择nth-child,只能通过元素类型选择。如果你添加另一个具有不同类的div,则奇偶数将全部移动。 - Waltur Buerk
我同意@WalturBuerk的观点。我尝试过这个,但结果不一致,后来才意识到有时会有一个不同类别的兄弟元素被计算在这个伪选择器中。很遗憾。 - The Qodesmith

10

3
也许当我们使用这个时,可以实现:
.item:nth-of-type(odd)  .description{background-color:orange;}  

或者。
.item:nth-child(odd) .description{background-color:orange;}

您可以查看我的截图:http://screencast.com/t/17g9joVj8Z
希望您能得到所需的内容。

0

你应该将nth-of-type设置为.item元素:

#container{width:100% height:100%;}
.item {float:left; width:250px; height:700px;}
.item img {width:250px; height:250px; float:left;}
.description {width:250px; height:450px; float:left; background-color:blue;}
.item:nth-of-type(even) .description {background-color:red;} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接