Demystifying <pre> and <code>
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:
<pre>
- 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.
<code>
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:
pre {
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
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?


Want an avatar? Get a gravatar! • You can link to this comment
Very helpful. I especially liked the styling options.
When I first started coding I was a little unclear on pre versus code tags, too. I just used whatever would make the finished layout look good in a browser. It took awhile to realize certain tags have a “correct” usage.
Want an avatar? Get a gravatar! • You can link to this comment
Thanks, Jason! Glad you enjoyed the article. I was confused for some time as well!
Want an avatar? Get a gravatar! • You can link to this comment
Is there something comparable that can be used in WordPress posts? Because within a post, the pre tag creates a grey box of copiable code.
Want an avatar? Get a gravatar! • You can link to this comment
Thanks
. Nice Post. Cleared the air for me.
I have only used ‘pre’ for displaying php arrays so far
Want an avatar? Get a gravatar! • You can link to this comment
Glad to see you can nest
within -- that's just what I had been looking for!Thanks for the info.
Want an avatar? Get a gravatar! • You can link to this comment
…nest CODE within PRE
don’t know why that disappeared from the comment?
anyway, thanks!