1

I have the following Demo:

#parent:nth-child(1) {
  color: blue;
}
<html>

<body>
  <div id="parent">
    <div>first child</div>
    <div>second child</div>
    <div>third child</div>
  </div>
</body>

</html>

I was expecting only the first child of the parent element to be blue, but instead they all are. Why is this?

Kareem Dabbeet
  • 3,838
  • 3
  • 16
  • 34
tom894
  • 459
  • 1
  • 3
  • 14

2 Answers2

6

The problem in your case is the way :nth-child works, basically you need to add it at the child/sibling level, not at the parent level (and since your parent has no different, your selector is basically just like #parent). With the selector in the way you have it, it taking it as if #parent is the first child you want to select, that's why it's all blue. Make a slight change and it'll be fine:

#parent div:nth-child(1) {
   color: blue;
}
<html>
   <body>
      <div id="parent">
         <div>first child</div>
         <div>second child</div>
         <div>third child</div>
      </div>
   </body>
</html>

Also, as George just mentioned below, this will apply to any first div occurrence that's a descendant of #parent, in your case it makes no difference but it might with a different structure, so if you just want to limit it to direct descendants, you can use the more specific selector #parent > div:nth-child(1)

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
0

It is because you have selected the parent in CSS, but did not select the element of its child name. Try this, I hope it will help you.

#parent div:nth-child(1) {
  color: blue;
   }
<html>

<body>
  <div id="parent">
    <div>first child</div>
    <div>second child</div>
    <div>third child</div>
  </div>
</body>

</html>
Aberrant
  • 3,423
  • 1
  • 27
  • 38
  • just bcoz u have selected parent in css but not selected element of child name. Try this one hope, will help you. Thanks – mahesh chippewar Aug 27 '19 at 17:42
  • Welcome Mahesh! You should put your explanation *in* the body of the answer instead of adding a comment; you can still [edit](https://stackoverflow.com/posts/57679774/edit) the answer after you've posted it. – George Aug 27 '19 at 17:52