Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nth-child(1) giving background color to entire body element instead of just div

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 ? I am newbie to CSS.

Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the specification:

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n. It is not required to have a parent.

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

The :nth-child(An+B [of S]? ) pseudo-class notation represents elements that are among An+Bth elements from the list composed of their inclusive siblings that match the selector list S

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading