Syntax highlighting enhances the readability of code snippets on our blog by adding visually distinct styles for keywords, variables, and other programming elements. One of the easiest and most popular libraries to implement syntax highlighting is Highlight.js.

What is Highlight.js?

Highlight.js is a lightweight JavaScript library that automatically detects and applies syntax highlighting to code blocks. It supports over 190 programming languages and provides several pre-built themes for styling. Best of all, it’s easy to set up and works out of the box!

Steps to Add Highlight.js to Our Blog

Follow these steps to integrate Highlight.js to our template:

Step 1: Include Highlight.js Files

Download Highlight.js or link it directly via a CDN. Add the following <link> and <script> tags to our template.

I using HTMLy for my blogging platform so open layout.html.php, and put it between the <head></head> element.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">

And for the JS file I put it before the </body> element end.

<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>

Step 2: Initialize Highlight.js

Activate Highlight.js by calling its hljs.highlightAll() method in a <script> tag or JavaScript file. I put it right below the JS file above, and become:

<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>

Step 3: Test Our Setup

Create code blocks in the post and load our blog in a browser and verify that code blocks are highlighted correctly. Modify the styles or layout if needed to blend with our blog’s design.

Step 4: Choose a Theme

Highlight.js offers multiple themes to style your code blocks. Replace default.min.css in the <link> tag (see first step) with a theme of your choice, such as dark.min.css or github.min.css.

I use Google Code style so:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/googlecode.min.css">

Explore the full theme gallery on the official website.

Read also: Add a Copy-to-Clipboard Button to Code Blocks