If I have HTML:
<div class="myClass">1</div>
<div class="myClass">2</div>
<div class="myClass">3</div>
Can I write a rule in my CSS that says:
.myClass {
/* only display the first instance of the class */
}
Rick Hitchcock is very close.
The correct selector is ~
, as in:
.myClass ~ .myClass {
display: none;
}
Explanation:
In CSS:
+
selector indicates an element which is an immediately subsequent sibling.~
selector indicates an element which is any subsequent sibling.Consequently, with the following markup:
<div class="myContainer">
<div class="myClass">1</div>
<img class="myImage" alt="My Image" />
<div class="myClass">2</div>
<div class="myClass">3</div>
</div>
If you declare:
.myClass + .myClass {
display: none;
}
then
<div class="myClass">3</div>
won't be visible, but
<div class="myClass">2</div>
will be visible.
Whereas, if you declare:
.myClass ~ .myClass {
display: none;
}
then neither
<div class="myClass">2</div>
nor
<div class="myClass">3</div>
will be visible.
This will hide all .myClass
elements that follow another .myClass
element:
.myClass + .myClass {
display: none;
}
It's basically the inverse of "only display the first instance of the class." In this case, it's "hide all but the first instance of the class."
Snippet:
.myClass + .myClass {
display: none;
}
<div class="myClass">1</div>
<div class="myClass">2</div>
<div class="myClass">3</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With