Here is my code
:nth-child(1) {
background-color: blue;
color: aliceblue;
}
<div>
<p>one</p>
<p>two</p>
<p>three</p>
<p>four</p>
<p>five</p>
</div>
Now div
is the first child of body
element, so its background color will be changed to blue. But I see that entire body’s background color is changed. body
element is actually second child of root html
element. What’s happening ?
3
Answers
It should be
p:nth-child(1)
.Simply adding
:nth-child(1)
without a parent selector will add the first element to the HTML snippet, which is thediv
tag.If you want that for the first
p
tag, the selector must be modified asp:nth-child(1)
From the specification:
The selector is more concerned by the siblings than the parent element so in your case the
html
element is also selected because it’s the first element among its siblings (it’s alone in that list)Even in the new version of the Specification, it’s always about siblings and never the parent
I’m guessing that you are trying to give the first paragraph element a blue background. You could use something like this below: