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 for 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 amoungst other specifics and may also include a desciption in a
All special symbols require encoding prior to use in a HTML document. Here's a table outlining the most commonly used HTML symbols.
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. If you need to know more see the PHP
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:
Note: contenteditable is spelt incorrectly in the example above because Google AMP incorrectly interprets it as a real property in this instance.
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.
There's an optional plug-in to add line numbering too.
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.
I apply SVGs wherever possible, especially on simple graphics like icons and repeated backgrounds. The stripe lines are perfect for it. They render very well at any resolution. Here's the SVG:
Yup, just 8 paths (lines) with the background colour defined in the CSS. Easy no? Hand-coded so I may of missed an optimisation but at around 400 bytes it hardly seemed worth it.
It's best to add as a
background to the
pre tag via CSS
and embedded as a data URI as Internet Explorer, bless, doesn't support SVG in the style sheet.
UPDATE: Internet Explorer (9+) does support raw SVG as CSS
background-images. You just need to convert the format. Though it appears
border-images still require embedding as a data URI. You can read more in Embedding SVG cross-browser.
Background properties are split into components for clarity:
Holes and tear line
This time we add an SVG as a
border-image to emulate punch-holes and tear-strips.
Adding it to the
code element. Note it must be in data URI format at the time of writing.
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
figcaption but I'm working on that currently. Considering something like:
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, well as yet, 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).
Add an expand button
Sometimes the horizontal space, in which a code block is placed, is limited by the design. This may be circumvented please see the article Expanding code blocks. It describes how the effect used on this page.
Though I've recently given up on that strategy and just use the