2013-02-20 51 views
31

非常感谢您提前给出的答复。如何使用CSS选择每个其他div类元素(无js)

我知道如何做到这一点使用JavaScript和PHP,但我想学习如何/如果有可能做到这一点只使用CSS。

我有一个容器,可容纳许多物品。每个项目都有一张图片,下面有一张包含说明的div。我希望描述的背景对于其他每个项目都是不同的。

是否有可能使用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> 

回答

42

你想在.itemnth-child()

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

演示:jsFiddle

+0

非常感谢! :) 令人敬畏的猫,哈哈 – Jaime 2013-02-20 18:15:02

+3

这是行不通的。你不能按类选择nth-child,只能通过元素类型。如果你添加另一个班与另一个班的赔率和平衡将全部转移。 – 2016-04-08 11:00:09

+0

我同意@WalturBuerk。我已经尝试过这种方式,并且对不一致的结果感到困惑,只有意识到有时候我有一个与此伪选择器中计数的不同类的兄弟姐妹。游民。 – 2016-09-28 23:44:13

0

你应该设置第n-的类型来.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;} 
2

也许这是可能的,当我们使用此:

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

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

你可以看到我的截图:http://screencast.com/t/17g9joVj8Z
我希望你得到你所需要的。