-1

I have the following HTML:

<html>
    <body>
        <div id="parent">
            <div>
                <div>A</div>
                <div>A</div>
                <div>A</div>
            </div>
            <div>
                <div>A</div>
                <div>A</div>
                <div>A</div>
            </div>
            <div>
                <div>A</div>
                <div>A</div>
                <div>A</div>
            </div>
        </div>
    </body>
</html>

and the following CSS:

#parent div:nth-child(2) {
  background-color: blue;
}

I was expecting the fourth, fifth, and sixth "A"s to be blue since I was trying to target only the second child of the element with ID parent, however, the second and eighth were also made blue. Why is this and how do I fix it?

Here is an image of my result: https://i.stack.imgur.com/FEB4N.png

And here is an image of my expected result: https://i.stack.imgur.com/MVrCn.png

tom894
  • 459
  • 1
  • 3
  • 14

2 Answers2

0

Your css code is targeting all secound childs of div's inside of #parent. You need to target only direct childs of #parent using the > selector:

#parent > div:nth-child(2) {
  background-color: blue;
}
<div id="parent">
    <div>
        <div>A</div>
        <div>A</div>
        <div>A</div>
    </div>
    <div>
        <div>A</div>
        <div>A</div>
        <div>A</div>
    </div>
    <div>
        <div>A</div>
        <div>A</div>
        <div>A</div>
    </div>
</div>
Christian Carrillo
  • 2,751
  • 2
  • 9
  • 15
0

Try this:

#parent > div:nth-child(2) {
  background-color: blue;
}

You see the second and eighth div blue because they are also "the second" children of #parent (relative to their parent div). Using '>' in CSS selector applies your style only to straight children div of #parent.

David
  • 161
  • 2
  • 6