skip to Main Content

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


  1. 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 the div tag.

    If you want that for the first p tag, the selector must be modified as p:nth-child(1)

    p: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>
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. I’m guessing that you are trying to give the first paragraph element a blue background. You could use something like this below:

    div p:first-of-type {
      background: blue;
      color: white;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search