如何仅使用CSS(无js)选择所有其他div类元素

Jai*_*ime 37 html css css-selectors css3

非常感谢您的回复.

我知道如何使用javascript和php来做到这一点,但我正在尝试学习如何使用css来实现这一点.

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

是否可以使用css实现这一目标?如果是这样,怎么样?我一直在使用选择器

.item:nth-child(odd){background-color:red}
.item .description:nth-of-type(odd){background-color:orange;}
Run Code Online (Sandbox Code Playgroud)

我似乎无法得到它.建议,评论,任何事情表示赞赏.再次感谢朋友们.下面是一些简化的示例代码,演示了我的目标.

<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>
Run Code Online (Sandbox Code Playgroud)

Thi*_*iff 56

你想要nth-child().item.

.item:nth-child(odd) .description {
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

演示: 的jsfiddle

  • 这不起作用.您不能按类选择nth-child,只能按元素类型选择.如果你用另一个类添加另一个div,那么几率和均衡都会发生变化. (3认同)
  • 非常感谢!:) 很棒的猫,哈哈 (2认同)

Eri*_*ves 8

.item:nth-child(even) {...}
.item:nth-child(odd) {...}
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/DuL24/1/