Search code examples
csscss-counter

Count hidden elements with CSS Counters


How can I not exclude a element from counting if it's set display: none;?

body {
  counter-reset: section;
}
.variant--name::before {
  counter-increment: section;
  content: counter(section) ": ";
}

.hidden {
  display: none;
}
<div class="variant--group">
<h3 class="variant--name">variant</h3>
</div>

<div class="variant--group hidden">
<h3 class="variant--name">variant</h3>
</div>

<div class="variant--group">
<h3 class="variant--name">variant</h3>
</div>


Solution

  • As the .hidden is giving the element display: none this is why the counter wouldnt work as its effectively not in the dom.

    I would maybe add a class (just incase .hidden else where needed to be display: none) of:

    .hiddenButAccessible {
      position: absolute;
      left: -9999px;
      max-height: 0px;
      overflow: hidden;
      opacity: 0;
    }
    

    here's a working example:

    http://codepen.io/sonnyprince/pen/oxqzzL