Adding Syntax Highlighting to Code Snippets in a Website

Warning
This article was last updated on 2022-04-10, the content may be out of date.

All rights and credits reserved to Tania Rascia. This is a rewrite (kind of) just for sake of simplicity.

Here we will use the JavaScript library to automatically highlight our code. There are various libraries but the most favorited are:

It’s your choice to pick one but in this guide, we will use Prism.js. If you want to local hosting your file. Download it here,

Or we can simply link the css in our <head>:

1
2
3
4
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.0/themes/prism.min.css"
/>

And link to the JS before the closing tag:

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.5.0/prism.min.js"></script>

Finally, wrap your desired code in <pre><code class="language-whatever">. You’re defining the language, and the <pre> ensures that all your indentation will be properly preserved.

1
2
3
<pre><code class="language-css">body{

}