Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 714
Francesco Avatar asked Jun 13 '26 07:06

Francesco


1 Answers

: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;
}
like image 126
BoltClock Avatar answered Jun 18 '26 00:06

BoltClock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!