同一类上的Css,2种样式,每个div切换样式

同一类上的Css,2种样式,每个div切换样式,css,html,Css,Html,我想在同一个重复div上有不同的背景色。 例如: 我知道我可以在服务器端为每个类打印不同的类,但是如果可能的话,我正在寻找一种在同一个类上用CSS打印的方法,而不添加类/id/Js。 谢谢。您可以使用:n子(n)选择器 div.test:nth-child(odd) { background-color: blue; } div.test:nth-child(even) { background-color: red; } 看看这里的例子 请注意,IE6、7、8不

我想在同一个重复div上有不同的背景色。 例如:


我知道我可以在服务器端为每个类打印不同的类,但是如果可能的话,我正在寻找一种在同一个类上用CSS打印的方法,而不添加类/id/Js。 谢谢。

您可以使用:n子(n)选择器

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

div.test:nth-child(even) {
    background-color: red;    
}
看看这里的例子

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

您可以使用:第n个子(n)选择器

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

div.test:nth-child(even) {
    background-color: red;    
}
看看这里的例子


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

这解决了您的问题:

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

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

这解决了您的问题:

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

您可以使用第n个子(偶数|奇数)选择器:

.test:nth-child(even) {background: blue}
.test:nth-child(odd) {background: red}
您可以在

中看到更多示例。您可以使用第n个子项(偶数|奇数)选择器:

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

您可以在

上看到更多示例,如果您不想添加第二个css类是因为HTML的大小,或者为了简单起见,您也不必使用“test”类,只要您可以找到一个包装这些类的容器元素

检查这把小提琴:


如果您不想添加第二个css类是因为HTML的大小,甚至是为了简单起见,那么您也不必使用“test”类,只要您能找到一个包装这些类的容器元素

检查这把小提琴:


+现场答题1分,现场答题+1分。