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