Home > Back-end >  nth-child selects everything
nth-child selects everything

Time:01-09

I'm trying to understand how the :nth-child works but don't understand why it is selecting everything below:

    :nth-child(2) {
        color: blue;
    }
<div>
    hello
    <h1>test</h1>
    <p>one</p>
    <p>two</p>
    <p>three</p>
    <p>four</p>
</div>

<div>
    <span>hey</span>
</div>

<p>hello</p>

test

Same happens when I do nth-child(1) but then nth-child(3) selects only "two" and "hello"

    :nth-child(3) {
        color: blue;
    }
<div>
    hello
    <h1>test</h1>
    <p>one</p>
    <p>two</p>
    <p>three</p>
    <p>four</p>
</div>

<div>
    <span>hey</span>
</div>

<p>hello</p>

test

Can somebody give me a walkthrough on how it's working so I can understand the concept?

CodePudding user response:

you forgot something. nth-child is a selector is selecting one specific item in your same list.look HTML, the h1 element is the second child of its parent div element, so it is selected and its color is set to blue. The other p elements are also the second child of their parent div element, so they are also selected and their color is set to blue.

so if you need color the "hey" , you need to upgrade the code to ,

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

you need color the "two", you need to upgrade the code to,

p:nth-child(2) {color :blue;}

you not done anything wrong. only you forgot select element in html.

I hope this help you.

CodePudding user response:

You can inspect an element to find out where it's getting its styles from. In Firefox, right-click an element and click Inspect to bring up the Developer Tools (there is a very similar procedure for Chrome):

Firefox Developer Tools showing an element inheriting the color property from the body element

We see here that <h1> is inheriting the color property from the <body>, which is selected because it's the 2nd child of <html>. Likewise, with :nth-child(1), <html> is matched and everything will inherit color from that. It's smart to use :nth-child() only with a combinator targeting a specific parent/ancestor so you don't have unexpected inheritances like that.

  • Related