Display the first specific element on the entire page
I am trying to display only the first element and hide all other elements.
Here's an example:
<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>
Is there a solution without JS?
+3
source to share
2 answers
Using :first-of-type
on h1
won't work, instead use that on the first one .content
h1
. For example:
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>
+6
source to share
.content ~ .content h1 {
display: none;
}
This is what I know as the shortest solution, it basically selects all h1 elements awaiting the first one.
Explanation: ~ selects all siblings (elements) after the first .content class that have a .content class
If you want to read further W3 Schools with W3 Examples Combined Siblings
0
source to share