Utilizing CSS counters and the <code>
element to display syntax highlighted code snippets with automatic line numbering:
HTML:
<code>
<div class="line"><span>line 1</span></div>
<div class="line"><span>line 2</span></div>
...
</code>
CSS:
code {
display: inline-block;
border: 1px black solid;
padding: 1em;
font-family: "Consolas", "Monaco", "Courier New", monospace;
counter-reset: line;
}
code .line {
display: block;
counter-increment: line;
}
code .line::before {
border-right: 1px black solid;
padding-right: 1em;
margin-right: 1em;
content: counter(line);
}
Functioning well for single-digit line numbers, but alignment issues arise when dealing with double digits:
Is there a way to align the left edges of the lines? Or perhaps right-align the line numbers?
Techniques already attempted include:
- works up to 99 lines but problematic at 100 and appearance is not idealcounter(line, decimal-leading-zero)
- Modifying content using JavaScript, however
just returnsgetComputedStyle(line, '::before').content
"counter(line)"