Search code examples
javascripthtmlcsscss-counterzero-padding

CSS Counter with a Number Padding


Is it possible to pad counter numbers depending on its value?

div {
  counter-reset: ruler;
}

div > span {
  display: block;
  line-height: 1rem;
}

div > span::before {
  counter-increment: ruler;
  content: counter( ruler ) ' ';
}
<div>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
  <span>Hello, World!</span>
</div>

Like if there are 42 lines, numbers will be like 09 or  9, 420 — 009 or   9.


Solution

  • Use decimal-leading-zero inside the counter.

    div {
      counter-reset: ruler;
    }
    
    div > span {
      display: block;
      line-height: 1rem;
    }
    
    div > span::before {
      counter-increment: ruler;
      content: counter( ruler , decimal-leading-zero) ' ';
    }
    <div>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
      <span>Hello, World!</span>
    </div>