我从 w3-schools 拿了这个例子(参见 link )。如果我定义我的 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>
一切正常,<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>
...
..<p>This paragraph is the first child of its parent (body).</p>
不再获得黄色背景。
为什么?我将 CSS 样式应用于所有第一个 p
元素。当我添加标题时,p
显然,这之后的元素仍然是第一个 p
元素。为什么它不起作用?
最佳答案
它仍然是第一个 p 元素,但它不再是第一个子元素(如示例文本所述)。当您将标题添加到顶部时,该标题将成为第一个子标题。
如果您想要每个父元素中的第一个 p 元素而不考虑其整体位置,请改用 p:first-of-type
。
关于html - 特定元素上的 CSS `:first-child`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23248432/