This does not work in a specific snippet, because if you look at the generated markup, you can see that the <style>
was moved to the body
and the first of p
became really the second element inside the body
.
console.log(document.body.innerHTML);
<!DOCTYPE html> <html> <head> <style> p:nth-child(2) { color: red; } </style> </head> <body> <p>Paragraph-1</p> <p>Paragraph-2</p> </body> </html>
To fix, you can instead use first-of-type
, or wrap the necessary elements in some container as in the next answer.
Or, as already indicated in the comments, do not insert the html, head, body tags into the markup, since they are still generated automatically, and the duplicate ones are simply removed. And use special fields in snippets for scripts, markup and css.
console.log(document.body.innerHTML);
p:first-child { color: red; }
<p>Paragraph-1</p> <p>Paragraph-2</p>
p
, they may already be on the page, and your style is assigned to them. Add a class to yourp.someClass:first-child { ... }
and check - Vasily Barbashevhtml, body, head
tags therehtml, body, head
. They already exist, and you break the page structure with this - Vasily Barbashev