← All posts

Syntax Highlighting with Google Prettify

· JavaScript, Tools

First appeared on mobifreaks.com · Updated

In 2012 I made the black-and-white code on Mobifreaks look pretty with Google Prettify. It took three steps.

The 2012 steps

1. Download Prettify, extract it (it came as a .tar.bz2, so you extracted twice with 7-Zip), and put the .js files in a js folder and the .css in a css folder. The lang-*.js files had to stay next to prettify.js.

2. Link the files and run Prettify when the page loads:

<link href="css/prettify.css" rel="stylesheet">
<script src="js/prettify.js"></script>
<body onload="prettyPrint()">

3. Add the class prettyprint to any pre or code:

<pre class="prettyprint">...</pre>

Today

Google archived Prettify in April 2020, and it is no longer maintained. If you are starting now, pick one of these instead:

  • Highlight at build time if you can. Static site generators and frameworks often have it built in. This site uses Astro, which highlights code blocks with Shiki while building the page, so readers download no extra JavaScript. Shiki uses the same grammars as VS Code, so the colours match what you see in your editor.
  • Highlight in the browser when you can't change the build, for example on a hosted blog. Prism and highlight.js both work by adding a script and a class, much like Prettify did:
<link rel="stylesheet" href="prism.css">
<pre><code class="language-css">body { margin: 0; }</code></pre>
<script src="prism.js"></script>

Whichever you choose, check the colour contrast of the theme. Many popular themes use comment colours that are too faint to read comfortably.