문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

p:first-child means select the first child of its parent if and only if it's a p element.

You want p:first-of-type which means select the first child p element.

More on first-child from MDN

The :first-child CSS pseudo-class represents any element that is the first child element of its parent.

vs first-of-type

The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element.

Try p:first-of-type, instead. Using p:first-child, I believe, selects any p elements that are also the first child of the parent element. When you add an h1 element in front of the p elements, then that h1 becomes the first child, so p:first-child is no longer valid.

p:first-child actually refers to any element <p> that is the first child of its parent.

When you add the <h1>, you are making it so that <p> is no longer the first child.

You may want to use p:first-of-type instead.

I use to solve that this way (just to be sure is compatible with old browsers):

p:first-child,
h1 + p {
    background-color:yellow;
}

This way you are going to work on all of the first child paragraph and all the paragraph that comes after every h1 (if you want to be more specific you could in this case improve the selector to "body > h1 + p")

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top