如何仅隐藏类型的第一个元素?

Bra*_*ley 10 css css-selectors

我有以下标记:

<div class="ctr-1">
    <h3>Title</h3>
    <div class="ctr-2">
        <h3>Title</h3>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

以及下面的CSS

.ctr-1 h3:first-child{ display:none; }
Run Code Online (Sandbox Code Playgroud)

两个<h3>标签都是隐藏的,我只想隐藏第一个标签.怎么样?

Boa*_*oaz 16

这就是first-of-typenth-of-type 选择是.

例如:

.ctr-1 h3:first-of-type { display:none; }
/* - Or - */
.ctr-1 h3:nth-of-type(0) { display:none; }
Run Code Online (Sandbox Code Playgroud)

这将隐藏第一个h3后代.ctr-1,无论它在父元素内的位置如何.

当然,在您的具体示例中,h3它确实也是immediate(>)和first(:first-child)的后代.ctr-1.但如果这是巧合,你可能无法依赖它.在那种情况下,nth-of-type是要走的路.


cru*_*ush 8

它们在技术上都是first-child.

在您的示例中,您可以:

.ctr-1 > h3:first-child { display:none; }
Run Code Online (Sandbox Code Playgroud)


Jos*_*ier 7

像这样:

.ctr-1 > h3:first-child {
    display:none; 
}
Run Code Online (Sandbox Code Playgroud)

jsFiddle在这里