我有这样的HTML:
<div class="container">
<div class="foo">Foo!</div> <!-- if this is red... -->
<div class="bar">Bar!</div>
</div>
<div class="container">
<div class="foo">Foo!</div> <!-- ...i want this blue... -->
<div class="bar">Bar!</div>
</div>
<div class="container">
<div class="foo">Foo!</div> <!-- ...and this red. -->
<div class="bar">Bar!</div>
</div>
我希望每一秒“foo”都有蓝色背景,另一个foo:s红色。
我试过了:
.container .foo:nth-child(odd)
{
background-color: red;
}
.container .foo:nth-child(even)
{
background-color: blue;
}
我也玩了一些nht-of-type,但是我无法让它发挥作用。 在上面的测试中,他们都是“奇怪的”,因为他们都变成了蓝色。
我做错了什么?
答案 0 :(得分:4)
您的nth-child
选择器位于错误的位置:
.container:nth-child(odd) .foo
{
background-color: red;
}
.container:nth-child(even) .foo
{
background-color: blue;
}
<强> jsFiddle example 强>
答案 1 :(得分:1)
您的选择器有点偏离。
他们应该在父母身上。
.container:nth-child(odd) .foo
{
background-color: red;
}
.container:nth-child(even) .foo
{
background-color: blue;
}