html - 仅当所选元素是 CSS 中特定父元素的第一个子元素时,样式才会应用

标签 html css css-selectors

我想了解如何选择 .if-first-child元素是特定父元素的第一个元素,在本例中为 <div> .

<div class="no-css">
    <p class="if-first-child">The style will only take effect here!</p>
    <p>No style here..</p>
    <p class="if-first-child">No style here..</p>
</div>
<div class="no-css">
    <nav>
        <p class="if-first-child">No style here..</p>
    </nav>
</div>

换句话说,例如我要申请background-color: black;.if-first-child仅当它是 <div> 的第一个 child 时.

请注意 div p:first-child选择器仍会选择 .if-first-child元素,即使它有一个 <nav> parent 。

最佳答案

无意中,我发现了在 div p:first-child 问题中暴露时如何选择目标选择器仍会选择 p:first-child元素如果它有 <div>祖 parent 。

div > .if-first-child:first-child { 
    background-color: black;
}

那只会针对第一个 child .if-first-child这是 <div> 的直系子代.它不会针对孙子.if-first-child:first-child .

关于html - 仅当所选元素是 CSS 中特定父元素的第一个子元素时,样式才会应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090831/

相关文章:

python - 无法找到元素 - 多个元素似乎具有相似且最少的信息,但我无法正确找到

html - 定位段落 <p> 元素的后代

javascript - 恒定高度 div 后跟占据所有空间的 div

Javascript 全屏 api 和窗口高度

html - 如何设置单个 WordPress 菜单项的样式?

html - 仅在图像的一半上应用 CSS 过滤器

jQuery 或 CSS 选择器选择所有以某个字符串开头的 ID

javascript - 从 Google 搜索结果中提取数据

python - 如果 user.is_authenticated for Django,模板无法正确呈现

javascript - li 元素溢出 Card 容器并增加父容器以适应自身