CSS3:nth-​​child()选择器如何工作?

时间:2016-04-27 14:01:53

标签: css css3

任何人都可以解释一下CSS3:nth-​​child()选择器的工作原理吗?

在下面的示例中,尽管<p>的值为2,但仍会选择第一个:nth-child(n)元素。

&#13;
&#13;
p:nth-child(2) {
    background: #ff0000;
}
&#13;
<h1>This is a heading</h1>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

<p><b>Note:</b> Internet Explorer 8 and earlier versions do not support the :nth-child() selector.</p>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:4)

该选择器将选择父母的第n个孩子的所有元素。在您的情况下,p是其父<body>的第二个孩子,因此会被选中。

运行此代码段以验证行为:

p:nth-child(2) {
  color: red;
}
<!-- body is a first parent -->
<body>
  <span>First child of body</span>
  <p>Second child of body</p>

  <!-- div is a second parent, whose children are also considered -->
  <div>
    <p>First child of div</p>
    <p>Second child of div</p>
  </div>
</body>

答案 1 :(得分:0)

理解nth-child属性的一个很好的例子可以是列表。

&#13;
&#13;
li:nth-child(2) {
  background: red;
 }
&#13;
<h1>This is a heading</h1>
<ul>
  <li>The first element.</li>
  <li>The second element.</li>
  <li>The third element.</li>
  <li>The fourth element.</li>
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

:nth-child(n)选择器匹配其父级的第n个子元素,无论其类型如何(即,在您的情况下为<body>)。您示例中的:nth-child(2)<p>The first paragraph.</p>

这里有一个例子,希望能说明这种类型不是重要的,而是子元素相对于其父元素的位置:

&#13;
&#13;
h1:nth-child(2) {
  background: #f00;
}

h2:nth-child(2) {
  background: #ff0;
}

h3:nth-child(2) {
  background: #f0f;
}

h4:nth-child(2) {
  background: #0ff;
}

h5:nth-child(2) {
  background: #00f;
}
&#13;
<h1>This is a h1 heading.</h1>
<h2>The is a h2 heading.</h2>
<h3>The is a h3 heading.</h3>
<h4>The is a h4 heading.</h4>
<h5>The is a h5 heading.</h5>

<h1>This is a h1 heading.</h1>
<h2>The is a h2 heading.</h2>
<h3>The is a h3 heading.</h3>
<h4>The is a h4 heading.</h4>
<h5>The is a h5 heading.</h5>
&#13;
&#13;
&#13;