Daniel Williams Daniel Williams - 19 days ago 7
CSS Question

Hiding elements with same class after first one displayed

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 */
}

Answer

You can use :first-of-type

 .myClass {
      display: none;
  }
 .myClass:first-of-type {
      display: block;
  }

  <div>
      <div class="myClass">1</div>
      <div class="myClass">2</div>
      <div class="myClass">3</div>
  </div>

This will hide all myClass elements except for the first one in the DOM. I have always felt this makes the most readable sense.