Using Code Examples in HTML

You can include code examples in your HTML by using the <code> tag. This automatically uses a monospaced font and also semantically labels our code as what it is.

The HTML

Say we wanted to show this CSS code on our page:

p { color: red; }
code { background-color: #eee; }

Here is an example of the HTML we put in our page to show it:

<pre>
  <code>
    p { color: red; }
    body { background-color: #eee; }
  </code>
</pre>

We use the <code> tag to indicate that our text is actually code. We use the <pre> tag because in this case, we actually want to browser to display the white space that we show. This allows the code to be spaced properly.

Styling the Code Block

In order to display the code properly and in an easy to read fashion, we need to style the <code> block. This page uses the following CSS styles to display the code block:
pre code {
  background-color: #eee;
  border: 1px solid #999;
  display: block;
  padding: 20px;
}

You can style your code blocks however you like. The important property to remember here is the display: block;. <code> is actually and inline HTML element. In order to get it to display in a nice block (like on this page), we use this CSS property to tell it to behave like a block.

Remember to Encode Your HTML Entities!!

If you want to use a code example that includes HTML, you must use HTML entities for your < and >. If you don't do this, it will be interpreted as actual HTML.