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

时间:2017-06-29 09:38:00

标签: html css

我试图只显示第一个元素并隐藏所有其他元素。

以下是一个例子:

<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>

有没有JS的解决方案吗?

2 个答案:

答案 0 :(得分:6)

:first-of-type上使用h1无法使用,而是在第一个.content h1上使用该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>
{{1}}

答案 1 :(得分:0)

DEMO

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

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

<强>说明: 〜在第一个具有.content类

的.content类之后选择所有兄弟(元素)

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