Embedding code samples
In this article I endeavor to incorporate all you need to know to produce beautiful code examples on your own pages.
Covering best practices, semantics, encoding symbols, visual styling and language syntax highlighting.
Best practices when displaying code
- Keep the number of lines low. It may be difficult to scroll horizontally if the scrollbar isn't in the viewport.
- Break large blocks into small more manageable chunks, as you would in the code itself. Perhaps provide explanations between the chunks?
- Aim for clarity not compression. Don't minify, or reduce white-space.
- Avoid long horizontal lines to maintain readability.
- Include comments to indicate why it's as is, and not what the code is doing.
- Avoid complexity. Generically speaking; Good code is simple code.
Firstly let's consider the HTML mark-up semantically.
We semantically mark-up the content by containing it within a
code tag, after all it is code.
pre tag indicates to the browser its contents are preformatted. So it appears in the browser the same as it appears in the HTML. If you need more info read Everything you need to know about the
figure element in HTML 5 was designed to contain code examples amongst other specifics and may also include a description in a
All special symbols (HTML entities) require encoding prior to use in a HTML document. Here's a table outlining the most commonly used HTML symbols.
Escaping HTML, with PHP
Alternatively, by using a small snippet of PHP, we no longer have to manually encode symbols (<, >, &, etc) into HTML entities (
This process used to be a royal pain in the proverbial but on applying a little PHP, we return the cream to the medicine cupboard.
Everything sitting between
EOD; will be automatically converted by PHP on the server. Please ensure the closing
EOD appears as the first characters on its own line. If you need to know more see the PHP
There are alternative HTML markup escaping methods available as extensions to the Prism highlighter, a little hacky though. See Syntactic sugaring later in this article for details.
You may of noticed I've allowed one HTML symbol to remain, the ellipsis.
An ellipsis is used to indicate an incomplete or partial fragment. Consider it as the correct way of writing
Yada, yada, yada. It's written as three horizontal dots (…) and coded
Very useful to indicate skipped pieces of irrelevant detail in code examples.
Editable code blocks?
The article Best Practice for Code Examples strongly suggests making code blocks editable for content navigation and selection, greatly improving accessibility and usability:
Now the code block is selectable via CTRL+A and the Home and End keys also work. Nice one James.
Styling (Part one)
We have a basic container, and our content is encoded, we can add basic styling.
That'd be considered pretty minimalistic but we'll get back to it.
word-wrap: normal added to
pre > code in Safari.
Okay, I mean language dependent syntax highlighting.
Personally I use, and recommend, the excellent Prism by Lea Verou and friends. It doesn't rely on external libraries. It's small, 1.6KB minified & gzipped, and languages, 0.3–0.5KB each, with colour themes, 1KB ish, too. Very highly recommended, don't take my word; Smashing Magazine, Sitepoint and CSS-Tricks use it too.
Alternatives? Yeah ok, take a look at:
So Prism it is then…
Prism requires the
code element to have a class stating the coding language:
As default I personally find these four enough, where
covers the occasional PHP function. Prism supports 111 languages, the choice is yours.
Customised Prism CSS comes with a few more tweaks (included in the themes).
Personally I remove
font-family leaving them to the cascade. I also reduce tab spacing to 2 characters and increase
line-height to 2.
So far so good, but that's all a bit boxy and plain. Hell, I couldn't even be bothered to show an example. Lets' do something about it.
Code area backgrounds
I like geek-retro cool; who doesn't? So I'll describe how to emulated that awful, cheap computer paper we had to use at college and Uni. I actually wonder if they still use it?
We are going to cover how to achieve the visual effect.
Updated for 2020 (draft update)
I've rewritten the "code paper" SVG so only one svg is required:
Also updated my personal version of prism.css to accommodate both dark and light modes:
I also created a simple cut & paste tool to Escape HTML entities for code embedding.
Display the code language
Another neat little CSS-Trick is to display the language in the code block. This was previously achieved using a snippet from CSS Tricks.
Though it would be better stated as part of a
Which would require:
You may of noticed there's an overlaid background image applied to the
code element? I found the SVG lines just a little too clean so I overlaid a little noise to take the edge off.
Or as an SVG.
A drop shadow was added to lift the code blocks above the page.
This was achieved using the
::after pseudo classes and applied to blocks which have the
Twisting the night away
Each code block has a small rotation added via CSS to disassociate it further from the page background. Giving them a “placed on table” look. It also displaces each character slightly, further enhancing the typewritten effect.
When I retro-fied the code blocks it looked a little too clean and decided to drop it in favour of, yes, you guessed, default monospace for a more “traditional code” look.
It also had the benefit of reducing the assets required which in turn improved page load speed. An all round improvement to my way of thinking.
While I don't use it personally, a copy-to-clipboard function may often be a good idea. I recommend the script clipboard.js to achieve this. I'll leave documentation to the providers but it's easy enough, doesn't use Flash, and small (less than 2Kb gzipped).
Expandable code area
Sometimes the horizontal space, in which a code block is placed, is limited by the design. This may be circumvented by using the