Code has been added to clipboard!

HTML pre Tag

Reading time 2 min
Published Jun 29, 2017
Updated Oct 2, 2019

HTML pre Tag: Main Tips

  • The <pre> tags surround the pre-formatted text.
  • Browsers display this content in a monospace font.
  • Whitespace and line breaks inside this element are preserved.
  • HTML <pre> tag supports all global attributes.

Using HTML <pre> Element

By wrapping text in HTML pre tags, you can keep its format with all the whitespace and line breaks you intend to use:

Example
<pre>
  The text in this
  block has fixed font style
  and font size, and also keeps
  line breaks, spaces, etc.
</pre>

The browser displays the text using these settings by default:

Example
pre {
    display: block;
    font-family: monospace;
    white-space: pre;
    margin: 1em 0;
}

Tip: pre HTML tags are useful when you want to include poetry or some characters made to resemble a graphic image (e.g., a concrete poem).

Attributes for pre Tag

There were three tag-specific attributes to HTML pre. However, you shouldn't use any of them due to very poor browser support. The first two are deprecated, and the third one has not been standardized.

Attribute Description
wrap Hinted how the overflow should be displayed.
cols Represented how many characters one line should contain.
width Represents how many characters one line should contain as well.
Technically still used, but does not create a visual effect.

Tip: instead of these attributes, use CSS width and white-space properties.

Making Pre-Formatted Images Accessible

Whenever you use HTML pre tags to convey a visual effect, you need to keep accessibility in mind. Spaces and line breaks might cause issues for technologies used by blind and visually impaired users (i.e., screen readers).

To prevent that, you should provide alternative text. Use <figure> tags with ARIA role and aria-labelledby attributes to identify your creation as an image and associate it to the caption. Then, add said caption wrapped in <figcaption> tags:

Example
<figure role="img" aria-labelledby="bunny">
	
 ___________
|           | 
| BITDEGREE | 
|    IS     | 
|  AWESOME  | 
|___________|
 (\__/) || 
 (•ㅅ•) || 
 /   づ

<figcaption id="bunny"> A bunny holding a sign that says "BitDegree is 
awesome". A picture is made out of text characters.
</figcaption>
</figure>

Browser Support

Chrome
All
Edge
All
Firefox
1+
IE
All
Opera
All
Safari
All

Mobile Browser Support

Chrome
All
Firefox
4+
Opera
All
Safari
All