注意:请参阅以下内容以获取更明确的解释
我想弄清楚为什么会这样。
HTML
<div class="chicken">
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
</div>
CSS
.chicken { width:100%; background:#999; float:left; }
.big-chix { width:48%; margin:0.5%; padding:0.5%; background:#666; float:left; }
.big-chix:nth-child(2n+1) { background-color:#eee; }
.big-chix:nth-child(2n+2) { background-color:#aaa; }
我在这里想要实现的是为第n个孩子1,3,5 ......以及2,4,6 ...... {/ 1}}提供不同的背景...
但是当我输入一个段落(或其他类似div等等)时,就会变成这样:
HTML
.big-chix
CSS
<div class="chicken">
<p>paragraphy</p>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
<div class="big-chix">Contento</div>
</div>
第n个孩子的位置切换位置。为什么会这样? .chicken { width:100%; background:#999; float:left; }
.big-chix { width:48%; margin:0.5%; padding:0.5%; background:#666; float:left; }
.big-chix:nth-child(2n+1) { background-color:#eee; }
.big-chix:nth-child(2n+2) { background-color:#aaa; }
仅假设选择所有.big-chix:nth-child()
类(6 .big-chix
),然后将1,3,5设置为.big-chix
background-color
},以及2,4,6到#eee
?
编辑:从我收集的内容来看,#aaa
将不会应用于代码中元素父元素中的元素子元素:
jsFiddle - nth-child(1) when <p>
paragraph is the first element
HTML
nth-child
CSS
<div class="chicken">
<p>paragraphy</p> [this is nth-child(1)]
<div class="big-chix">Contento</div> [this is nth-child(2)]
<div class="big-chix">Contento</div> [this is nth-child(3)]
<div class="big-chix">Contento</div> [this is nth-child(4)]
<div class="big-chix">Contento</div> [this is nth-child(5)]
<div class="big-chix">Contento</div> [this is nth-child(6)]
<div class="big-chix">Contento</div> [this is nth-child(7)]
</div>
但是,它将在以.chicken { width:100%; background:#999; float:left; }
.big-chix { width:48%; margin:0.5%; padding:0.5%; background:#666; float:left; }
.big-chix:nth-child(1) { background-color:#eee; }
作为第一个元素的父元素中工作。
jsFiddle - nth-child with .big-chix
as the first element
HTML
.big-chix
CSS
<div class="chicken">
<div class="big-chix">Contento</div> [this is nth-child(1)]
<p>paragraphy</p> [this is nth-child(2)]
<div class="big-chix">Contento</div> [this is nth-child(3)]
<div class="big-chix">Contento</div> [this is nth-child(4)]
<div class="big-chix">Contento</div> [this is nth-child(5)]
<div class="big-chix">Contento</div> [this is nth-child(6)]
<div class="big-chix">Contento</div> [this is nth-child(7)]
</div>
答案 0 :(得分:9)
不是.big-chix:nth-child()只想选择所有.big-chix类(6 .big-chix),然后将1,3,5设置为背景颜色#eee,以及2,4,6到#aaa?
没有
:nth-child()
选择“父级中的第n个元素”,而不是“与选择器的其他部分匹配的第n个元素”。
每个选择器都是独立应用的,只有匹配所有组件的元素才会匹配完整的选择器。
但请注意,:nth-of-type()
应该可以达到你想要的效果。
答案 1 :(得分:-2)
使用这些
.big-chix:nth-child(even) { background-color:#eee; }
.big-chix:nth-child(odd) { background-color:#aaa; }