Skip to main content

Easily add example code to your web page. Beautifully handles JavaScript, CSS, HTML, and PHP. Minimum fuss—Maximum effect.

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.

I'll even throw in how to expand the code area and copying to the clipboard using JavaScript. How's that for a package?

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.

Example <pre><code> block

Firstly let's consider the HTML mark-up semantically.

Language HTML
<figure>
  <figcaption>Your code title</figcaption>
  <pre>
    <code>
      <!-- your code here -->
    </code>
  </pre>
</figure>

We semantically mark-up the content by containing it within a code tag, after all it is code.

Using the 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 pre element.

The figure element in HTML 5 was designed to contain code examples amoungst other specifics and may also include a desciption in a figcaption block.

Parsing special characters

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 (&lt;, &gt;, &amp;, etc).

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.

Language HTML
<pre><code><? $str = <<<'EOD'
  <!-- your code here -->
  EOD;
  $str = htmlspecialchars($str, ENT_HTML5, ENT_NOQUOTES);
  $str = str_replace("&amp;hellip;", "&hellip;", $str);
  echo($str);?>
</code></pre>

Everything sitting between 'EOD' and EOD; will be automatically converted by PHP on the server. If you need to know more see the PHPhtmlspecialchars function.

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 &hellip;.

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:

Language HTML
<figure>
  <figcaption>Your code title</figcaption>
  <pre>
    <code contenteditible spellcheck="false">
      <!-- your code here -->
    </code>
  </pre>
</figure>

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.

Language CSS
pre, code {
  font-family: monospace, monospace;
}
pre {
  overflow: auto;
}
pre > code {
  display: block;
  padding: 1rem;
  word-wrap: normal;
}

That'd be considered pretty minimalistic but we'll get back to it.

Note: contenteditable requires word-wrap: normal added to pre > code in Safari.

Syntactic sugaring

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:

Language HTML
<code class="language-markup">
<code class="language-css">
<code class="language-clike">
<code class="language-javascript">

As default I personally find these four enough, where clike 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 color, background-color, and font-family leaving them to the cascade. I also reduce tab spacing to 2 characters and increase line-height to 2.

Language CSS
code[class*="language-"],
pre[class*="language-"] {
  text-shadow: 0 1px #fff;
  direction: ltr;
  text-align: left;
  white-space: pre;
  word-spacing: normal;
  word-break: normal;
  word-wrap: normal;
  line-height: 2;
  -moz-tab-size: 2; -o-tab-size: 2; tab-size: 2;
  -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none;
}

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.

Stripy lines

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:

Language HTML
<svg width="1224" height="64" stroke-width='2' stroke='#EDF3ED' viewBox="0 0 1224 64" xmlns="http://www.w3.org/2000/svg">
  <path d="M0,0L1224,0"/>
  <path d="M0,4l1224,0"/>
  <path d="M0,8l1224,0"/>
  <path d="M0,12l1224,0"/>
  <path d="M0,16l1224,0"/>
  <path d="M0,20l1224,0"/>
  <path d="M0,24l1224,0"/>
  <path d="M0,28l1224,0"/>
</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:

Language CSS
pre {
  …
  background-color: #FCFDFC;
  background-repeat: repeat-y;
  background-position: 0 -1rem;
  background-size: auto 4rem;
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg stroke-width='2' stroke='%23EDF3ED' width='1224' height='64' viewBox='0 0 1224 64' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0,0L1224,0'/%3E%3Cpath d='M0,4l1224,0'/%3E%3Cpath d='M0,8l1224,0'/%3E%3Cpath d='M0,12l1224,0'/%3E%3Cpath d='M0,16l1224,0'/%3E%3Cpath d='M0,20l1224,0'/%3E%3Cpath d='M0,24l1224,0'/%3E%3Cpath d='M0,28l1224,0'/%3E%3C/svg%3E");
}

Holes and tear line

This time we add an SVG as a border-image to emulate punch-holes and tear-strips.

Language HTML
<svg width="40" height="100" viewBox="0 0 40 100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="19" cy="49" r="14" style="fill:#fdfdfd;stroke-width:2;stroke:#ddd"/>
  <circle cx="19" cy="51" r="14" style="fill:#FAFAFD;stroke-width:0"/>
  <path d="M40,0l0,100" style="fill:none;stroke-width:2;stroke-dasharray:2,6,2,6;stroke:rgba(184,217,184,.7)"/>
</svg>

Adding it to the code element. Note it must be in data URI format at the time of writing.

Language CSS
pre > code {
  …
  border-image: url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwIDAgNDAgMTAwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxjaXJjbGUgY3g9IjE5IiBjeT0iNDkiIHI9IjE0IiBzdHlsZT0iZmlsbDojZmRmZGZkO3N0cm9rZS13aWR0aDoyO3N0cm9rZTojZGRkIi8+PGNpcmNsZSBjeD0iMTkiIGN5PSI1MSIgcj0iMTQiIHN0eWxlPSJmaWxsOiNGQUZBRkQ7c3Ryb2tlLXdpZHRoOjAiLz48cGF0aCBkPSJNNDAsMGwwLDEwMCIgc3R5bGU9ImZpbGw6bm9uZTtzdHJva2Utd2lkdGg6MjtzdHJva2UtZGFzaGFycmF5OjIsNiwyLDY7c3Ryb2tlOnJnYmEoMTg0LDIxNywxODQsLjcpIj48L3BhdGg+PC9zdmc+Cg==") 0 0 0 400 repeat;
}

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.

Language CSS
pre > code[class]::before {
  content: attr(class);
  display: block;
  font-size: small;
  font-style: italic;
  color: #6c5f7c;
  margin: -.4rem 0 .6rem -1.2rem
}

Though it would be better stated as part of a figcaption but I'm working on that currently. Considering something like:

Language HTML
<figure>
  <figcaption>Language of code</figcaption>
  <pre>
    <code>
      <!-- your code here -->
    </code>
  </pre>
</figure>

Which would require:

Language CSS
figure {
  position: relative;
}
figcaption {
  position: absolute;
  top: 1.3rem;
  left: 2.5rem;
  font-size: small;
  font-style: italic;
  color: #6c5f7c;
}
pre > code {
  …
  padding-top: 3rem;
}

Grainy paper

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.

Language CSS
pre > code {
  …
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAABlBMVEX///////9VfPVsAAAAAnRSTlMAuyogpzwAAABJSURBVHhehcCxEQJBCADAhSEgJLCA+xkLwc4+MDC0ZEtwAb2rYdWbc3iEcRZgdEJ5QQKe/oPUjL0LIZhdBFfMqHRDca709QnwA8AYBjw1mzYyAAAAAElFTkSuQmCC);
}

Or as an SVG.

Language CSS
pre > code {
  …
  background-image:url("data:image/svg+xml;charset=utf8,%3Csvg width='1200' height='256' viewBox='0 0 1200 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cdefs%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.3,.1'%3E%3C/feTurbulence%3E%3C/filter%3E%3C/defs%3E%3Crect height='256' width='1200' filter='url(%23noise)' opacity='.1'/%3E%3C/svg%3E");
}

Corner lifts

A drop shadow was added to lift the code blocks above the page.

This was achieved using the ::before and ::after pseudo classes and applied to blocks which have the class="shadowlift".

Language CSS
.shadowlift {
  position: relative;
  margin: 1.5rem 0 2.5rem;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
.shadowlift::before,
.shadowlift::after {
  content: "";
  z-index: -1;
  position: absolute;
  width: 48%;
  top: 80%;
  bottom: 0.5rem;
  box-shadow: 0 0.5rem 0.5rem rgba(119, 119, 119, 0.6);
}
.shadowlift::before{
  left: 0.5rem;
  transform: rotate(-2deg);
}
.shadowlift::after{
  right: 0.5rem;
  transform: rotate(2deg);
}

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.

Language CSS
.shadowlift:nth-child(2n) {transform: rotate(-0.3deg);}
.shadowlift:nth-child(3n) {transform: rotate(-0.2deg);}
.shadowlift:nth-child(4n) {transform: rotate(0.3deg);}
.shadowlift:nth-child(5n) {transform: rotate(-0.4deg);}

Fonts

I started this project using what I personally considered as the best font for displaying code – Source Code Pro. Which I mixed with Source Sans Pro for body copy and Lato for headings.

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.

Language CSS
pre, code, kbd {
  font-family: monospace, monospace;
}

Add copy-to-clipboard

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 resize property.

Language CSS
pre {
  …
  overflow: hidden;
  resize: horizontal;
  min-width: 100%
}

Socialise: