nth-child selector in css

2019-08-22 11:24发布

问题:

i am curious to know how the nth-child css selector works. I was expecting the following code to change the background color for the 3rd

element, that is "The third paragraph". However, when I run this code, the 2nd

element is getting selected and "The second paragraph" has a changed background color.

<html>
<head>
<style> 
p:nth-child(3) {
    background: #ff0000;
}
</style>
</head>
<body>

<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>

</body>
</html>

回答1:

Since <p> is not a child of any ancestor and it cordially counts <h1>, you need to use :nth-of-type to target the third paragraph

p:nth-of-type(3) {
    background: #ff0000;
}

Fiddle



回答2:

nth-child does not care for the type of the other elements, so it also counts the h1 element.

You can archive what you want using p:nth-of-type(3)

EDIT: Clarification



回答3:

In this case, you're specifying a paragraph that is the nth-child of it's parent. Since the parent is body, and you're asking for n to be 3, it will be the second p in your markup.