html - 特定元素上的 CSS `:first-child`

标签 html css css-selectors

我从 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/

相关文章:

html - ng-bind-html 指令在呈现时删除样式属性

javascript - 如何控制轮播中视频的暂停/播放?

javascript - 鼠标离开时在 anchor 标签上反向悬停

n 个 float 元素上的 css nth-child 选择器

jQuery 选择器 : logical OR

html - 定位 anchor 元素中的文本而不是图像

html - 用 Iframe(jsfiddle) 填充空白

javascript - 使用 jquery 或 javascript 重新加载 div 或脚本而不是页面的随机按钮

html - 固定子元素在 Firefox 浏览器中闪烁

html - 如何将此文本与图像对齐?