GreyRoofPigeon
GreyRoofPigeon

Reputation: 18123

nth-child style not applied

So, I have bumped into the following problem. I'm trying to give the "heading" all a different color using nth-child.

My HTML looks like this:

<header>
    <h1>Title<br />
    <span>Subtitle</span></h1>

    <p><strong>Heading</strong><br />
    text</p>
    <p><strong>Heading</strong><br />
    text</p>
    <p><strong>Heading</strong><br />
    text</p>
</header>

And my CSS looks like this:

header h1 {
    font-size: 4em;
    line-height: .65em;
}
header h1 span {
    font-size: .5em;
}
header p {
    font-size: .9em;
}
header p strong {
    font-size: 1.1em;
}
header p:nth-child(1) strong { color: #f3b200; }
header p:nth-child(2) strong { color: #d27b26; }
header p:nth-child(3) strong { color: #dc572e; }

Without the <h1>, it works perfectly, check this Fiddle.

But with the <h1>, it seems to see the <h1> as a <p>. Making the last "heading" not having a color. Check the Fiddle.

I don't understand why this happens.

Upvotes: 3

Views: 456

Answers (2)

andyb
andyb

Reputation: 43823

By adding another element (the <h1>) the indices you use in the selectors are now off by 1. You might have noticed that the heading colours in your second demo have shifted up by one position also.

You could just increase the indices on the original CSS to select the new positions

header p:nth-child(2) strong { color: #f3b200; }
header p:nth-child(3) strong { color: #d27b26; }
header p:nth-child(4) strong { color: #dc572e; }

but the better solution is to use a different CSS selector nth-of-type pseudo-class which takes the actual element into consideration, as already shown in Mr. Alien's answer.

Upvotes: 0

Mr. Alien
Mr. Alien

Reputation: 157334

Because if nth-child didn't found the nth number of element matching p element, so it will fail, use nth-of-type instead

header p:nth-of-type(1) strong { color: #f3b200; }
header p:nth-of-type(2) strong { color: #d27b26; }
header p:nth-of-type(3) strong { color: #dc572e; }

Demo

Upvotes: 4

Related Questions