我想了解如何选择 .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/