csscss-counter

Using css counters to generate ordinal values?


I'm guessing this isn't possible, but wondering if anybody has attempted to produce ordinal numbers (1st, 2nd, 3rd etc) using CSS Counters with any success?

Obviously this would be trivial in JavaScript, but was hoping to find a style-only solution.


Solution

  • It will be easy if you have to add th on every number. But in this case you will need to change the 1st, 2nd, 3rd, 21st, 22nd, 23rd, 31st, 32nd, etc...

    So you will need to use nth child concept here. Use :nth-child to target the element.

    You will also need to use :not selector to not change the 11th, 12th, 13th element

    body {
      margin: 0;
      font: 13px Verdana;
    }
    
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
      counter-reset: item;
    }
    
    ul li {
      margin-bottom: 5px;
      position: relative;
    }
    
    ul li:before {
      counter-increment: item;
      content: counter(item)"th. ";
      color: red;
      font-weight: bold;
    }
    
    ul li:nth-child(10n+1):not(:nth-child(11)):before {
      content: counter(item)"st. ";
    }
    
    ul li:nth-child(10n+2):not(:nth-child(12)):before {
      content: counter(item)"nd. ";
    }
    
    ul li:nth-child(10n+3):not(:nth-child(13)):before {
      content: counter(item)"rd. ";
    }
    <ul>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
      <li>listItem</li>
    </ul>