Right alignment of CSS counters in :: before pseudo-element

I use CSS counters and the <code> tag to show the syntax of the selected code snippets with automatically generated line numbers:

Jsfiddle

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); } 

It works well up to 9 lines, but as soon as it types two digits, it goes out of alignment:

css counters

How to align the left edges of the lines? Or align the line numbers correctly?

I already tried:

  • counter(line, decimal-leading-zero) - it works up to 99 lines, but it breaks into 100, and I don’t like how it looks.
  • Changing content using JavaScript, but getComputedStyle(line, '::before').content just returns "counter(line)"
+4
source share
1 answer

You can use display:inline-block; and width based on your practical needs:

Demo: http://jsfiddle.net/zXsXU/14/

 code .line::before { display:inline-block; width:2em; border-right: 1px black solid; padding-right: 1em; margin-right: 1em; content: counter(line); } 
+2
source

Source: https://habr.com/ru/post/1480611/


All Articles