Syntax highlighting with Google prettify: Adding Numbers
First appeared on mobifreaks.com · Updated
A follow-up to Syntax Highlighting with Google Prettify: how to number every line of code.
The 2012 way
Prettify turned each line into an item of an ordered list when you added the class linenums:
<pre class="prettyprint linenums"><code>...</code></pre>
By default it only numbered every fifth line. To show a number on every line, I removed these rules from prettify.css:
li.L0, li.L1, li.L2, li.L3, li.L5, li.L6, li.L7, li.L8 { list-style-type: none; }
li.L1, li.L3, li.L5, li.L7, li.L9 { background: #eee; }
Prettify has since been archived, so here is how I would do it now.
Line numbers with CSS counters
Most highlighters (Shiki, Prism, highlight.js) can wrap each line in its own element, for example <span class="line">. With that in place, a CSS counter adds the numbers:
pre code { counter-reset: line; }
pre code .line::before {
counter-increment: line;
content: counter(line);
display: inline-block;
width: 2.5ch;
margin-right: 1.5ch;
text-align: right;
color: #8b8b8b;
user-select: none;
}
user-select: nonekeeps the numbers out of the selection when someone copies the code.- Prism also has a Line Numbers plugin if you'd rather not write the CSS.
Line numbers help when you refer to specific lines in the text. For short snippets they mostly add noise, so I only turn them on for long examples.