EDDYMENS

Published 2 years ago

Highlight.js: Add Line Numbers

HighlightJS [↗] does not provide line number feature out of the box. You will need a third-party library for that.

Fortunately, there are a number of them to choose from. The one used in the example code below is by Yauheni Pakala [↗].

To use the library you first need to pull it in either as a node module or using a CDN, then initialize highlightJS i.e.: hljs.highlightAll()

Then after that execute hljs.initLineNumbersOnLoad(); to apply line numbering.

NB: Do note that the example below uses the CDN version of all the libraries.

Visit the official repo [↗] to learn about the different options available with the library.

01: <pre> 02: <code> 03: function name() { 04: console.log("output") 05: } 06: </code> 07: </pre> 08: 09: <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script> 10: 11: <script src="https://cdn.jsdelivr.net/npm/highlightjs-line-numbers.js/dist/highlightjs-line-numbers.min.js"></script> 12: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlightjs-themes@1.0.0/androidstudio.css"/> 13: 14: <script> 15: hljs.highlightAll(); // initialize highlighting 16: hljs.initLineNumbersOnLoad(); // apply line numbering 17: </script>

You may use the CSS style below in the collapsible to better enhance the snippet display.

Extra CSS
01: <style>
02:    /* for block of numbers */
03:    .hljs-ln-numbers {
04:    -webkit-touch-callout: none;
05:    -webkit-user-select: none;
06:    -khtml-user-select: none;
07:    -moz-user-select: none;
08:    -ms-user-select: none;
09:    user-select: none;
10:    text-align: center;
11:    color: #ccc;
12:    border-right: 1px solid #CCC;
13:    vertical-align: top;
14:    padding-right: 5px;
15:    /* your custom style here */
16:    }
17:    /* for block of code */
18:    .hljs-ln-code {
19:    padding-left: 10px;
20:    }
21: </style>

Here is another article you might like 😊 Horizontally aligning list items (li) within an unordered list (ul)