小编典典

:nth-​​child(n)前面的空格有什么作用?

css

当我编写一些CSS时,在使用外观之前从未遇到过这种情况,:nth-child(n)并且我怀疑实际发生了什么。

使用伪类时,我会在选择器之间没有空格的情况下编写它们,如下所示:

div#wrap:hover {
    border-bottom: 2px solid orange;
}
/* OR */
div#wrap:nth-child(4) {
    border-bottom: 2px solid orange;
}

但是它没有按我预期的方式工作,所以我尝试在选择器和伪类之间插入一个空格。令人惊讶的是,它的工作原理是:

div#wrap :nth-child(4) {
    border-bottom: 2px solid orange;
}

使这项工作发生了什么事?

div#wrap :nth-child(4) {

  border-bottom: 2px solid orange;

}


<div id="wrap">

  <h1>Heading 1</h1>

  <p>This is a test!</p>

  <h2>Creating content</h2>

  <p>The next paragraph uses the <strong>.html</strong> method to create a new element.</p>

</div>

阅读 905

收藏
2020-05-16

共1个答案

小编典典

您误会了选择器。它选择的元素也是,:nth-child(n)该元素 也具有 前面的元素作为父元素。

如果前面没有选择器,则默认为 *:nth-child(n)

因为您可能只想将其应用于直接后代,而不是将每个元素应用于其父代的第四个子代和父代的后代,所以我.element > *:nth- child(n)只能将其应用于直接后代。

div#wrap > *:nth-child(4) {
  border-bottom: 2px solid orange;
}



div#wrap > *:nth-child(4) {

  border-bottom: 2px solid orange;

}


<div id="wrap">

  <h1>Heading 1</h1>

  <p>This is a test!</p>

  <h2>Creating content</h2>

  <p>The next paragraph uses the <strong>.html</strong> method to create a new element.</p>

</div>

如果您想更加具体,并且仅选择第四个子<p>元素,则可以使用.element > p:nth- child(n)。这将选择所有<p>div#wrap选择器匹配的元素的第四个直接后代的元素。

div#wrap > p:nth-child(4) {
  border-bottom: 2px solid orange;
}



div#wrap > p:nth-child(4) {

  border-bottom: 2px solid orange;

}


<div id="wrap">

  <h1>Heading 1</h1>

  <p>This is a test!</p>

  <h2>Creating content</h2>

  <p>The next paragraph uses the <strong>.html</strong> method to create a new element.</p>

</div>

如果要选择<p>直接从each降序的第二个元素div#wrap,可以这样使用.element > p:nth-of-type(n)

div#wrap > p:nth-of-type(2) {
  border-bottom: 2px solid orange;
}



div#wrap > p:nth-of-type(2) {

  border-bottom: 2px solid orange;

}


<div id="wrap">

  <h1>Heading 1</h1>

  <p>This is a test!</p>

  <h2>Creating content</h2>

  <p>The next paragraph uses the <strong>.html</strong> method to create a new element.</p>

</div>
2020-05-16