Make the world a better place, one bug at a time.

Adding Line Numbers to Highlight.js

Adding Line Numbers to Highlight.js
Sunday, 6 July 2014 by @giancarlo84

The Problem

I needed a fast syntax highlighting library for one of my projects, so I found Highlight.js. The only problem was that it currently does not support line numbers.

This is a quick trick I used to automatically add line numbers, and their respective anchors, using CSS and some Javascript.


Numbers aligned to the left demo

Numbers aligned to the right demo2

The Code


The following code creates the <a> tags, assigns them a class and a name. The function should run relatively fast, depending on how many lines are added. It can also be easily modified if you don't use jQuery.


This is the CSS magic.

highlight.js syntax-highlight