Styling Code Snippets

The primary reason for building this blog was to document progress as I learn to code, and because that means posting lots of code, I wanted to find a way to style code snippets (as I’ve seen done on many sites). At first it looked like I would have to implement some kung-fu regex to do so, but then I discovered highlight.js, which does exactly that.

It’s crazy simple to use. Simply link the library to your stylesheet and hook it up to the page load event.

<link rel="stylesheet" href="styles/default.css">
<script src="highlight.pack.js"></script>

You can select from a range of styles. I chose rainbow.

Sidenote: I spent hours trying to figure out why highlight.js would refuse to style html snippets. I tried fixing my installation of highlight.js, and then I tried going with prism.js, an alternate syntax highlighter, both to no avail. It turns out the way you indicate html snippets in markdown is different from how you indicate other code snippets. With html you simply indent, whereas with other code (eg. css, ruby, etc.) you actually use <pre><code>...</code></pre>.

Lesson learned.

comments powered by Disqus