The <code> and <pre> tags

The <code> Tag

When you want to display text specifically as code, the <code> </code> tag set should be used. This informs the browser that the contained text should not be rendered as real code, but should be visually displayed on the web page as example code. Most browsers, by default, will format the text in a monospace font – just like in Notepad.

For example, to visually display the following code on a web page:
<p>paragraph text here.</p>

The actual (x)html code would look like this:
&lt;p&gt;paragraph text here.&lt;/p&gt;

Important to remember:

  • The <code> tag should be nested in a block-level tag, but not vice versa.
  • Do not use the <code> tag to format any miscellaneous text in a monospace font. Use it only for its intended purpose, to display code.

Reset Text with <pre> Tag

You must have noticed by now, that tabs, spaces, and enter breaks do not affect the actual rendered spacing on your web page. Well, there is a way around that.

When the <pre> </pre> tag set is used, any tabs, spaces, or enter breaks will render exactly as is. It is “pre-formatted” text.

Important to Remember

  • Be careful when using the <pre> tag. It should not be used to align text on the page. It is generally used similarly to the <code> tag to display coding blocks on your page. Always make sure to view your page in a smaller browser window to ensure that any longer lines of text do not cause a horizontal scroll bar.
  • Do not use any other formatting tags in the <pre>tag, although the <code> tag can be contained inside a <pre> tag.
  • Do not nest any block-level tags inside the <pre>tag. It is okay to nest the <pre> tag inside a <div>tag, but <p> and <hx> tags are no-no’s.
  • Most browsers will visually display the pre-formatted text with a monospace font.
  • If you want to format the <pre> text to display in a different font or color, you can easily define CSS styles for it by using the “pre” selector in a CSS rule.


Examples of both the<pre> and <code> tags:

Examples of Pre-formatted Text

Below you will find some examples of pre-formatted text using the <pre> and <code> tags.

First Example

This is the first line of text.
and this is the second line of text.
I am not using any line break tags;
Because the text is nested in a pre tag,
all "enter" breaks will be formatted literally.

Second Example

This example will show how 	tabbed	 text
contained in a pre tag will be formatted literally.

Third Example

Some example code that will visually display on the web page

<h2>Third Example</h2>
<p>Some example code that will visually display on 
the web page</p>

This tutorial is created by debbie T on November 5th, 2007 and originally posted at

%d bloggers like this: