Sunday, August 3, 2014

CSS Counter Property

While customizing my blogger template I needed a way to count lines for my formatted source code (the snippets like this one) and display them. Luckily CSS (since 2.1) has a counter built-in for us.

CSS

  • .tg-code {
  •     counter-reset: sc;
  • }
  • .tg-code li:before
  • {
  •     counter-increment: sc;
  •     content: counter(sc) ". ";
  •     margin-right:8px;
  • }

  • The above CSS is applied to the <code> HTML tag. Inside the <code> tag I used list items (<li>) for each line of code. On Line 2 we reset the counter to zero. Line 5 is saying "before the <li> HTML tag where we have the class .tg-code". Line 7 increments the counter. Line 8 defines the content to display back to the screen.

    HTML

  • <code class="tg-code">
  •     <li>source code line here</li>
  • </code>

  • Mozilla Docs - CSS Counters
    https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters
    W3C Recommendations
    http://www.w3.org/TR/CSS21/generate.html#counters

    No comments: