在整个页面上显示第一个特定元素

3
我尝试只显示第一个元素并隐藏所有其他元素。
下面是一个例子:
<style>
    h1 {
        display: none;
    }

    h1:first-of-type{
        display: block;
    }
</style>

<body>
    <div class="content">
        <h1>Test</h1> <!-- only this one should be visible -->
        123
    </div>
    <div class="content">
        <h1>ABC</h1>
        def
    </div>
</body>

有没有不需要使用 JavaScript 的解决方案?


1
当某些事件发生时,您希望发生什么?如果是的话,很可能需要使用JavaScript。如果不是,我猜您可以使用nth-child - Manos Kounelakis
其实我需要这个来打印,因为突然Chrome有点问题。 - Mr.Tr33
两个h1都可见,因为它们都是div中的第一个元素。 - Mr.Tr33
2个回答

6

h1 上使用 :first-of-type 不起作用,应该在第一个 .contenth1 上使用。像这样:

h1 {
    display: none;
}

.content:first-of-type h1 {
    display: block;
}

    h1 {
        display: none;
    }

    .content:first-of-type h1{
        display: block;
    }
    <div class="content">
        <h1>Test</h1>
        123
    </div>
    <div class="content">
        <h1>ABC</h1> 
        def
    </div>


0

演示

.content ~ .content h1 {
    display: none;
}

这是我所知道的最短解决方案,它基本上选择除第一个之外的所有h1元素。

解释: ~ 选择具有.content类的第一个元素后面的所有同级元素(包括.content类)

如果您想进一步阅读 W3 Schools with examplesW3 sibling combinators


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接