Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right-align CSS counters in ::before pseudo-element

Tags:

html

css

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:

css counters

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 looks
  • Altering the content with JavaScript, but getComputedStyle(line, '::before').content just returns "counter(line)"
like image 262
Tom Smilack Avatar asked May 14 '13 01:05

Tom Smilack


People also ask

What does :: Before mean in CSS?

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.

What is :: before and :: after?

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.

How do you align pseudo elements?

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".

How do you select before an element in CSS?

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.


1 Answers

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);
}
like image 60
Arbel Avatar answered Sep 21 '22 09:09

Arbel