Make code listings on your web page look pretty

20.11.2020 Reading time: 10min

As software developer we have to deal with source code practically every day. It's a thing we take for granted these days that our IDE shows us source code nicely styled, formatted and tailored to the programming language we use. However, what if we want to present pieces of our code on a website, like I want to do on this blog. Now, things look a lot different as the browser does not have much capability built in to do this. Before you start diving deep into custom CSS, read on because there is a better and more efficient way.

Laying the foundation

Before we dive into the actual formatting part, let's take a short look again how a code listing should be implemented in our markup to be semantically correct.

  
    
<code>
  <?php
    echo "Hello World";
  ?>
</code>

  

The wrapping tag does not much more than changing the font family to Monospace and providing a grey background. That's not a lot so we can do better.

highlight.js

The promise of this library is to enable syntax highlighting for the web in an easy manner. On their website they show the different styles and languages they provide which looks pretty neat. So, let's take a look what we have to do to enhance our simple code block with syntax highlighting for PHP.

Installing

Installing is as simple as executing

  
    
npm install highlight.js

  

If you are in a non-npm environment you could also include it via a simple script tag.

Usage

The only thing you have to do is importing the JavaScript which provides the functionality and one of the 97 code style you want to apply.

  
    
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'

  

To apply highlighting simply execute

  
    
hljs.initHighlighting()

  

highlight.js now automatically searches for code elements in your HTML and applies proper syntax highlighting according to the selected style. It even tries to detect the language automatically. However, I recognized that it is more safe to tell highlight.js about it which can be done by specifying class="language-<lang>" for the code element. That's actually all. Now your code block looks much better.

Conclusion

To wrap it up, highlight.js makes sense when you use code listings regularly on your website as on a software engineering blog like this. Especially when you have code listings with different languages, it pays off. The drawback is that we have to load external JavaScript which takes time to download respectively execute and blocks rendering.

© 2020 Jürgen Ratzenböck, All rights reserved - Privacy Policy