Using CSS counters, is it possible to set a class that displays a counter in a :before, but have the initial value of that counter be set for each use of the class?
For example, If I am showing line numbers using the css and html below, can I create a class that allows me to say to start the line numbers from 7 instead of 1, or, do I have to create a unique class for every block that I want to start at a different initial counter value?
pre { counter-reset: line; }
code{ counter-increment: line; }
code:before{ content: counter(line); }
<pre><code>Line of code</code></pre>
You can supply an arbitrary starting value to counter-reset
, but you'd need to do this with each pre
element using its inline style
attribute, and you'd need to supply a number 1 less than your desired starting line number:
pre { counter-reset: line; }
code { counter-increment: line; }
code::before { content: counter(line); float: left; margin: 0 1ch; }
<pre style="counter-reset: line 6"><code>Line of code</code></pre>
As you can imagine, this is incredibly hacky (I'm not referring to your implementation of line numbers here, since it's not the focus of your question, and my statement applies to any implementation that makes use of CSS counters however robust), but there is no other CSS-only solution (and you might even consider the use of inline styles "not CSS-only", which is perfectly understandable). This is why the majority of implementations use JavaScript in some shape or form to make it a little easier on the end user (the author).
If only browsers supported attr()
with properties other than content
, this would be made completely trivial, but alas, they don't, so the following hypothetical solution isn't going to work:
pre { counter-reset: line; }
pre[data-line] { counter-reset: line calc(attr(data-line integer) - 1); }
code { counter-increment: line; }
code::before { content: counter(line); float: left; margin: 0 1ch; }
<pre data-line="7"><code>Line of code</code></pre>