I'm using CSS counters and the <code>
tag to show syntax highlighted 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 once it hits two digits, it gets out of alignment:
How can I make the left edges of the lines align? Or right-align the line numbers?
I've already tried:
counter(line, decimal-leading-zero)
- it works up to 99 lines, but it breaks at 100, and I don't like the way it looksgetComputedStyle(line, '::before').content
just returns "counter(line)"
In CSS, ::before creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
The ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.
You need to position the :before pseudo-element absolutely by using the well known centering technique (use the top, left, and transform properties). Here, -25px will offset the text above the circle. Note that for the <span> element, we set the position property to its "relative" value and the display to "block".
The CSS ::before selector can be used to insert content before the content of the selected element or elements. It is used by attaching ::before to the element it is to be used on. In the example above we are prepending an asterisk and a space before every paragraph element on the page.
You can use display:inline-block;
and a 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With