Hiding items with one class after the first display
3 answers
You can use :first-of-type
.myClass { display: none; } .myClass:first-of-type { display: block; } <div class="myClass">1</div> <div class="myClass">2</div> <div class="myClass">3</div> This will hide all myClass elements except the first in the DOM. I have always felt that this makes the most readable meaning.
+1
Rick Hitchcock is very close.
The correct selector is ~ , as in:
.myClass ~ .myClass { display: none; } Explanation:
In CSS:
- The
+selector indicates the element that is immediately the next sibling. - The
~selector indicates an element that is any subsequent brother.
Therefore, 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> will not be visible but
<div class="myClass">2</div> will be displayed.
If you declare:
.myClass ~ .myClass { display: none; } neither
<div class="myClass">2</div> neither
<div class="myClass">3</div> will be displayed.
+6