Francesco
Francesco

Reputation: 25269

CSS first-child selector doesn't select first element

Why if I put an element before the "p" lines, I don't see the first line yellow? Should p:first-child select the very first p and not just a very first tag?

<style type="text/css">
    p:first-child 
    {
        background:yellow;
    }
</style>


<i></i>
<p>I am a strong man. I am a strong man.</p>
<p>I am a strong man. I am a strong man.</p>
<p>I am a strong man. I am a strong man.</p>

Upvotes: 3

Views: 2225

Answers (1)

BoltClock
BoltClock

Reputation: 724542

:first-child does not care about the type. By adding <i></i> to your code, i becomes the first child (assuming <style> is within <head> and the rest is in <body>, of course). Your selector wants to match p, but since p is not the first child anymore, your style can't be applied.

If you want to filter by type, use the CSS3 :first-of-type pseudo-class:

p:first-of-type
{
    background:yellow;
}

Upvotes: 10

Related Questions