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/

相关文章:

javascript - 使用 Javascript 淡入/淡出

html - 我怎样才能使 Zoom in mobile 像在 PC 上一样......?

html - CSS nth-child 所有元素显示为 "odd"

javascript - 为什么 CSS 选择器返回一个元素数组?

html - 无法使用html标签<audio>播放 'wav'文件

html - 如何修复悬停在透明照片上的问题

html - Ant Design Table 扩展改变 CSS 类 | react

javascript - 将鼠标悬停在区域上时如何避免 CSS 闪烁?

php - 找不到图像时的图像高度和宽度

css - svg 伪背景图像文件未在实时站点上显示但在本地主机上工作为什么?