Categories
HTML/CSS

automatically count headers via css

CSS 2.1 introduced counters which can be used to auto number your headings or other elements. You can define a counter, which will incremented for every element of a specific class or it will reset an other counter.

A simple example would be to automatic prefix all h2 and h3 tags with automatic numbering. The counter will be used in a :before pseudo element for output.

h1 {
  counter-reset: h2counter;
}

h2:before {
  content: counter(h2counter) ".\0000a0\0000a0";
  counter-increment: h2counter;
  counter-reset: h3counter;
}

h3:before {
  content: counter(h2counter)"."counter(h3counter) ".\0000a0\0000a0";
  counter-increment: h3counter;
  counter-reset: h4counter;
}

“\0000a0” is the NO-BREAK-SPACE Unicode Character.