Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS `:first-child` on specific element

I took this example from w3-schools (see the link). If I define my p:first-child to have a yellow background like this:

<!DOCTYPE html>
<html>
<head>
    <style>
        p:first-child {
            background-color:yellow;
        }
    </style>
</head>

<body>
    <p>This paragraph is the first child of its parent (body).</p>

    <h1>Welcome to My Homepage</h1>
    <p>This paragraph is not the first child of its parent.</p>

    <div>
        <p>This paragraph is the first child of its parent (div).</p>
        <p>This paragraph is not the first child of its parent.</p>
    </div>

</body>
</html>

Everything works fine and <p>This paragraph is the first child of its parent (body).</p> as well as <p>This paragraph is the first child of its parent (div).</p>get the yellow background.

But when I then add a headline right before the first p element, like this:

...
<body>

    <h1>test</h1>
    <p>This paragraph is the first child of its parent (body).</p>
...

.. the <p>This paragraph is the first child of its parent (body).</p> no longer gets the yellow background.

Why? I applied the CSS style to all of the first p elements. When I add a headline, the p element after this is, obviously, still the first p element. Why doesn't it work then?

like image 449
sqe Avatar asked Dec 05 '22 06:12

sqe


1 Answers

It's still the first p element, but it's no longer the first child (as described by the sample text). When you add the heading up top, that heading becomes the first child.

If you want the first p element in each parent regardless of its overall position, use p:first-of-type instead.

like image 63
BoltClock Avatar answered Dec 29 '22 12:12

BoltClock