我有一个包含 2 个可能类别的标签列表:P1 和 P2。我想将 CSS 应用于每个类的第一项。它在我的元素和 fiddle 中都不起作用
这是为什么?
.A>.B>.C>.P1:first-child {
font-weight: bold;
}
.A>.B>.C>.P2:first-child {
font-style: italic;
}
;
<div class="A">
<div class="B">
<div class="C">
<p class='P1'>
"JAJA P1"
</p>
<p class='P1'>
"JAJA P1"
</p>
<p class='P2'>
"JAJA P2"
</p>
<p class='P2'>
"JAJA P2"
</p>
</div>
</div>
</div>
最佳答案
:first-child
表示“该元素是其父元素内的第一个子元素”。这并不意味着“该元素是其父元素中的第一个子元素匹配其他条件”。
虽然有 :first-of-type
伪类,但没有 :first-of-class
伪类。 CSS 不直接支持你想要实现的目标。
你可以接近它,它支持你想设置的特定属性,用 general sibling combinator .
.p2 { font-style: italic; }
.p2 ~ .p2 { font-style: normal; }
您将所有匹配元素设置为斜体,然后将后续元素设置为非斜体。
关于html - CSS:定位每个类的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43806504/