HTML pre tag tutorial

HTML pre tag (<pre>) represents a block of preformatted text. By default pre tag does not collapse white spaces, and uses monospaced (fixed-width) font like courier. Some possible use cases of pre element tag:

  • To display emails text
  • To display code snippets
  • To display text art

Note that other tag like div can also produce behaviour similar to pre tag with appropriate css style (using white-space, font-family, etc).

Example – pre tag

This is basic pre tag example. Note that overflow is visible here.

<style>
pre {
  background-color: lightgreen;
  width: 200px;
}
</style>
<pre>
This      text is inside pre tag.
Second line of the text.
It may have      multiple spaces.
</pre>
refresh

Example – pre tag with auto scroll

We can use overflow:auto to add scroll automatically.

<style>
pre {
  background-color: lightgreen;
  width: 200px;
  height:60px;
  overflow:auto;
}
</style>
<pre>
This      text is inside pre tag.
Second line of the text.
It may have      multiple spaces.
</pre>
refresh

Example – pre tag – wrap long lines

We can use white-space:pre-wrap to wrap long lines. Note that it will still preseve multiple spaces.

<style>
pre {
  background-color: lightgreen;
  width: 200px;
  height:60px;
  overflow:auto;
  white-space:pre-wrap;
}
</style>
<pre>
This      text is inside pre tag.
Second line of the text.
It may have      multiple spaces.
</pre>
refresh

Related

Specification

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments