Align code line numbers with CSS

Viewed 3321

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?

2 Answers

You can do it with CSS Grid. The width of line numbers increases dynamically so you wouldn't get any error in future with big numbers. Take a look at below;

pre {
  counter-reset: line 0;
  display: grid;
  grid-template-columns: min-content 1fr;
  grid-auto-rows: 1em;
  gap: 0.3em;
}

.line-number {
  text-align: right;
}

.line-number::before {
  counter-increment: line;
  content: counter(line);
  white-space: pre;
  color: #888;
  padding: 0 .5em;
  border-right: 1px solid #ddd;
}
<pre>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
<span class="line-number"></span>
<code>Code</code>
</pre>

Related