Skip to main content Accessibility Feedback

Using the Prism.js syntax highlighter

Prism.js is a fantastic front-end syntax highlighter by Lea Verou.

Unlike many of the other options I’ve tried, Prism.js is incredibly lightweight and the highlighting is absolutely beautiful. I added it to the Go Make Things, Kraken, and all of the add-ons last week. It’s made the code a lot more readable.

Select your options

Head over the download page and select your options:

  • Development version or minified production version.
  • Theme of choice (I use the default).
  • Coding languages to support (CSS, Markup, JS and PHP for me).
  • Plugins like line highlighting and numbering.

Your options are dynamically updated as you make selections, which is actually just a bit annoying as it adds some latency into the process. When you’re ready, click the download buttons to grab you CSS and JS files.

Adding the files to your site

The JavaScript file can get added to your site as is, but I like to make a few updates to the default stylesheet.

First, I remove all of the styling related to the code and pre elements. I’ve already got my preferred styling for that (I use the defaults included in Kraken).

Next, I prefix all of the .token* related styles with pre, as I only want the syntax highlighting to apply to large blocks of code and not the inline stuff. (Yes, over-prefixing is bad for performance. Whatever.) Then, I wrap all of those styles in an @media screen {} media query. I don’t want highlighting for print styles.

@media screen {
    pre .token.comment,
    pre .token.prolog,
    pre .token.doctype,
    pre .token.cdata {
        color: slategray;
    }
    ...
}

Adding the markup

Lea works for the W3C, and has designed Prism.js to encourage good authoring practices. No special Prism.js specific classes are required, but you do need to adhere to W3C recommendations in order for it work.

You have to wrap code in a code element for highlighting to work, even for large blocks of preformatted text:

<pre><code>Code goes here</code></pre>

Additionally, Prism.js uses the HTML5 draft class=“language-*” specification to apply to appropriate highlighting.

<pre><code class="language-css">
    .example {
        font-size: 2em;
    }
</code></pre>

I don’t use any of the plugins, so I can’t comment on line numbering or highlighting, but the end result is fast, lightweight, beautiful syntax highlighting.