Css在同一个类,2个样式,每个div的开关样式

时间:2014-07-17 03:20:32

标签: html css html5

我希望在相同的重复div上有不同的背景颜色。 例如:

<div class="test"></div> <!-- this div bg color will be blue -->
<div class="test"></div> <!-- this div bg color will be red-->
<div class="test"></div> <!-- this bg div color will be blue -->
<div class="test"></div> <!-- this bg div  color will be red-->
<div class="test"></div> <!-- this bg div color will be blue -->
<div class="test"></div> <!-- this bg div  color will be red-->
<div class="test"></div> <!-- this bg div color will be blue -->
<div class="test"></div> <!-- this bg div  color will be red-->
<div class="test"></div> <!-- this bg div color will be blue -->
<div class="test"></div> <!-- this bg div  color will be red-->
<!-- and more and more, you got the idea... -->

我知道我可以在服务器端为每个打印不同的类,但我正在寻找一种方法在同一个类的CSS中执行此操作,如果可能的话,而不添加类/ ids / Js。 谢谢。

4 个答案:

答案 0 :(得分:2)

这解决了您的问题:

.test:nth-child(odd) {
    background: blue;
}
.test:nth-child(even) {
    background: red;
}

fiddle

答案 1 :(得分:1)

您可以使用:nth-​​child(n)选择器。

div.test:nth-child(odd) {
    background-color: blue;
}

div.test:nth-child(even) {
    background-color: red;    
}

查看此处的示例http://www.w3schools.com/cssref/sel_nth-child.asp

请注意,IE6,7,8不支持此选择器。

答案 2 :(得分:1)

您可以使用nth-child(偶数|奇数)选择器:

.test:nth-child(even) {background: blue}
.test:nth-child(odd) {background: red}

您可以在http://www.w3.org/Style/Examples/007/evenodd.en.html

看到更多示例

答案 3 :(得分:1)

如果您对不添加第二个css类的担忧是HTML的大小,或者为了简单起见,您不必使用“测试”。或者,只要你能找到一个包装那些的容器元素。

检查这个小提琴:http://jsfiddle.net/BuddhiP/aq3uz/

<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>

CSS是

.container div {
height: 1em;    
}


 .container div:nth-child(odd) {
    background: blue;
   }
   .container div:nth-child(even) {
    background: red;
   }