cssprecss-counter

Align code line numbers with CSS


I'm trying to insert line numbers in code snippets on my website (https://qscintilla.com/custom-lexer-example/), using a pure CSS approach (no javascript):

enter image description here

As you can see on the screenshot above, I'm building my website in Wordpress. I use the "Additional CSS" feature from the latest Wordpress version to insert custom CSS. Here is my custom CSS:

pre{
    counter-reset: line;
}
code{
    counter-increment: line;
}
code:before{
    content: counter(line);
    display: inline-block;
    border-right: 1px solid #ddd;
    padding: 0 .5em;
    margin-right: .5em;
    color: #888;
    -webkit-user-select: none;
}

It works pretty good, when I'm inserting code snippets in my HTML like so:

<pre>
<code> This is my first codeline </code>
<code> This is my second codeline </code>
<code> This is my third codeline </code>
<code> This is my fourth codeline </code>
</pre>

Unfortunately, the line numbers don't get aligned properly when the code line reaches double digits. Let's zoom in on the problem:

enter image description here

Of course, the same problem arises when the code line jumps from double to triple digits

How can I fix this?


Solution

  • If you want a pure CSS solution, there is only one way: use a fixed-width solution, i.e. explicitly declare a width on the ::before pseudo-element. However, this approach is never future-proof as you will have to account for scenarios where the counter might run into 3, 4, or more digits.

    pre {
      counter-reset: line;
    }
    
    code {
      counter-increment: line;
    }
    
    code::before {
      content: counter(line);
      display: inline-block;
      width: 1.5em; /* Fixed width */
      border-right: 1px solid #ddd;
      padding: 0 .5em;
      margin-right: .5em;
      color: #888;
      -webkit-user-select: none;
    }
    <pre>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    <code>Code</code>
    </pre>