I’ll admit that I was a little mystified by the <pre> and <code> tags. If you’re not sure which to use and when, here’s a quick guide:
- is short for pre-formatted text.
- is displayed in a fixed-width font (such as Courier).
- preserves both spaces and line breaks.
You want to use <pre> when you need to display text exactly as you typed it. Keep in mind that all spaces, tabs, and carriage returns will be preserved- which is why it’s a popular format for publishing poetry. For example, this:
<pre>Hello, I am pre-formatted text.</pre>
will show you:
Hello, I am pre-formatted text.
According to the W3C, <code> “designates a fragment of computer code”. This is what to use to display code in HTML- it’s semantically correct.
Here’s an example of using both <pre> and <code> to display a block of code. This:
<pre><code> code here and code here more code and more code </code></pre>
will show your visitors this:
code here and code here more code and more code
Styling <pre> and <code>
Now that you know which to use and when, it’s easy to set styles for these tags with CSS. You can, for example, choose to add padding and/or margins with borders around all instances of your <code>, or changing the default fixed-width font for all <pre> elements to something else. When styling <pre>, you might want to add this white-space definition so that your text wraps according to the user’s browser width, like so:
Finally, if you’re going to be posting a lot of code snippets using tags, you’ll want to use these characters:
< displays “less than” or <
> displays “greater than”, or >
Do you use <pre> and <code> in your HTML?