前面的空格是什么:nth-​​child(n)呢?

csa*_*ida 0 css css-selectors

虽然我正在编写一些CSS,但在使用之前我从未遇到过这种情况,我:nth-child(n)怀疑实际发生了什么.

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

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

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

div#wrap :nth-child(4) {
    border-bottom: 2px solid orange;
}
Run Code Online (Sandbox Code Playgroud)

发生了什么使这项工作?

div#wrap :nth-child(4) {
  border-bottom: 2px solid orange;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

小智 5

你误解了选择器.它选择前面的元素.element:nth-child(n)是其父元素的第n个子元素.

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

Because you probably only want to apply this to direct descendants and not every element which is the fourth child of its parent and a descendant of the parent, I would use .element > *:nth-child(n) to only apply to direct descendants.

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

div#wrap > *:nth-child(4) {
  border-bottom: 2px solid orange;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

If you wanted to be more specific and only select the fourth child if it is a <p> element, you can use .element > p:nth-child(n). This will select all <p> elements that are the fourth direct descendant of elements matching the div#wrap selector.

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

div#wrap > p:nth-child(4) {
  border-bottom: 2px solid orange;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

If you want to select the second <p> element directly descending from each div#wrap, you can use .element > p:nth-of-type(n) like so:

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

div#wrap > p:nth-of-type(2) {
  border-bottom: 2px solid orange;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)