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>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>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>Related
- CSS overflow - visible, hidden and scroll for overflowing content
- CSS white-space - collaping and wrapping of whitespaces and newlines
- CSS text-overflow - truncate text with three dots
- CSS clip