Presenting code with syntax highlighting

When it comes to presenting computer code on the web, there really aren’t any fast and hard rules, other than perhaps to just make the code visibly distinct from the primary text content.

In HTML, the <code> and <pre> tags are commonly used to present text as code, with specific styling defined through CSS.

Here’s a presentation of some code taken from the CSS for this blog:

div.sidebar {
    background-color: var(--blogTextColor);
    border-radius: 3px;
    color: var(--sidebarTextColor);
    padding: var(--sidebarPadding);
    margin-bottom: var(--paragraphSpacing); /* shares same bottom margin as paragraphs */
}

I created this styling to really make the code stand out against its background, as well as the rest of the content on the page. But we can go even further, and do what’s known as syntax highlighting.

div.sidebar {
    background-color: var(--blogTextColor);
    border-radius: 3px;
    color: var(--sidebarTextColor);
    padding: var(--sidebarPadding);
    margin-bottom: var(--paragraphSpacing); /* shares same bottom margin as paragraphs */
}

In doing so, the code is much clearer to parse through, when you’re trying to analyze what’s there. So, how you do make your code multi-colored according to the syntax? Well, you can certainly do the coloring yourself, but that would be rather tedious with a lot of manual coding.

Fortunately, there’s Prism, an excellent resource that can do all the work for you. It’s a CSS and JavaScript library that takes the code you’re presenting and automatically highlights the syntax.

Here’s Prism at work with some HTML code taken from my homepage.

Prism offers plenty of color themes as well as a plethora of third-party plugins that offer special functionality, such as adding line numbering to your code presentations.

Sometimes, however, I’ll just apply my own syntax highlighting to emphasize specific portions of code, such as the shape-outside and shape-margin CSS properties in this snippet.

img {
    float: left;
    shape-outside: url(heart.png);
    shape-margin: 20px;
}

Sharing your code is always pretty cool, whether to show off something special or be resourceful to your audience. Syntax highlighting just makes it all the more worthwhile.