我有以下标记:
<div class="ctr-1">
<h3>Title</h3>
<div class="ctr-2">
<h3>Title</h3>
</div>
</div>
和下面的 CSS
.ctr-1 h3:first-child{ display:none; }
两者都是 <h3>
标签是隐藏的,我只想隐藏第一个。怎么办?
最佳答案
这就是first-of-type
和 nth-of-type
选择器用于。
例如:
.ctr-1 h3:first-of-type { display:none; }
/* - Or - */
.ctr-1 h3:nth-of-type(0) { display:none; }
这将隐藏 .ctr-1
的第一个 h3
后代,无论它在父元素中的位置如何。
当然,在您的特定示例中,h3
确实也是直接 (>
) 和第一个 (:first-child
) 后代的 .ctr-1
。但如果这是巧合,你可能无法依靠它。在这种情况下,nth-of-type
是正确的选择。
关于css - 如何只隐藏类型的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18772494/