1
2

Hiding items with one class after the first display

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 */ } 
+5
source share
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
source

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
source

This will hide all .myClass elements that follow another .myClass element:

 .myClass + .myClass { display: none; } 

Basically this is the inverse of "only displays the first instance of the class." In this case, it will "hide everything except the first instance of the class."

Excerpt:

 .myClass + .myClass { display: none; } 
 <div class="myClass">1</div> <div class="myClass">2</div> <div class="myClass">3</div> 
+2
source

Source: https://habr.com/ru/post/1260100/


All Articles