关于特定元素的CSS`:first-child`

sqe*_*sqe 4 html css css-selectors

我从w3-schools那里拿了这个例子(见链接).如果我定义我p:first-child的黄色背景如下:

<!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>
Run Code Online (Sandbox Code Playgroud)

一切正常,<p>This paragraph is the first child of its parent (body).</p><p>This paragraph is the first child of its parent (div).</p>获得黄色背景.

但是当我在第一个p元素之前添加标题时,如下所示:

...
<body>

    <h1>test</h1>
    <p>This paragraph is the first child of its parent (body).</p>
...
Run Code Online (Sandbox Code Playgroud)

.. <p>This paragraph is the first child of its parent (body).</p>不再获得黄色背景.

为什么?我将CSS样式应用于所有第一个p元素.当我添加标题时,p显然这之后的元素仍然是第一个p元素.为什么它不起作用呢?

Bol*_*ock 6

它仍然是第一个p元素,但它不再是第一个子元素(如示例文本所述).当您向上添加标题时,该标题将成为第一个孩子.

如果您想要每个父级中的第一个p元素而不管其整体位置,请p:first-of-type改用.


SW4*_*SW4 5

p:first-child表示当且仅当它是一个元素时选择其父级的第一个子级p

您想要p:first-of-type这意味着选择第一个子p元素。

更多first-child来自 MDN 的内容

:first-child CSS 伪类表示作为其父元素的第一个子元素的任何元素。

first-of-type

:first-of-type CSS 伪类表示其父元素的子元素列表中该类型的第一个同级。