注意:请参阅下文以获得更清晰的解释
我试图弄清楚为什么会这样。
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; }
我在这里想要实现的是.big-chix
为第 n 个孩子 1、3、5... 和 2、4、6... 的班级设置不同的背景。
但是当我输入一个段落(或其他任何类似 div 等的内容)时,它变成了这样:
HTML
<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>
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 个孩子放置交换位置。为什么会这样?不.big-chix:nth-child()
只是假设选择所有.big-chix
类(即 6 .big-chix
),然后将 1, 3, 5 设置为 a background-color
of #eee
,并将 2, 4, 6 设置为#aaa
?
编辑:据我所知,nth-child
将不适用于以下代码中的元素父元素中的元素子元素:
jsFiddle - 当<p>
段落是第一个元素时的 nth-child(1)
HTML
<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>
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(1) { background-color:#eee; }
但是,它将在具有.big-chix
作为第一个元素的父元素中工作。
jsFiddle - nth-child.big-chix
作为第一个元素
HTML
<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>
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(1) { background-color:#eee; }