Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding elements with same class after first one displayed

Tags:

css

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 */
}
like image 892
Daniel Williams Avatar asked Nov 21 '16 23:11

Daniel Williams


2 Answers

Rick Hitchcock is very close.

The correct selector is ~, as in:

.myClass ~ .myClass {
display: none;
}

Explanation:

In CSS:

  • the + selector indicates an element which is an immediately subsequent sibling.
  • the ~ 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.

like image 68
Rounin - Glory to UKRAINE Avatar answered Sep 20 '22 13:09

Rounin - Glory to UKRAINE


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>
like image 34
Rick Hitchcock Avatar answered Sep 17 '22 13:09

Rick Hitchcock