Briefly
The <pre>
tag (from the English preformatted text) is used to display preformatted text when it is necessary to preserve all spaces and line breaks in HTML.
Example
<pre aria-label="Image of a cat, constructed from text characters."> ../\„„./\. .(='•'= ) . .(") „. ("). . \,\„„/,/ . │„„. „│ . /„/„ \„\ .(„)''l l''(„) . .. ((... . . . )).. . . .((..</pre>
<pre aria-label="Image of a cat, constructed from text characters."> ../\„„./\. .(='•'= ) . .(") „. ("). . \,\„„/,/ . │„„. „│ . /„/„ \„\ .(„)''l l''(„) . .. ((... . . . )).. . . .((.. </pre>
How to understand
In HTML code, the browser collapses all spaces into one and ignores line breaks.
If we place our cat in a regular <div>
, we will see it like this:
../\„„./\. .(='•'= ) . .(") „. ("). . \,\„„/,/ . │„„. „│ . /„/„ \„\ .(„)''l l''(„) . .. ((... . . . )).. . . .((..
To preserve the original formatting as in HTML, one can use the <pre>
tag.
Attributes
All global attributes can be applied to the <pre>
tag.
Tips
💡 By default, browsers use monospaced system fonts collectively known as monospace for displaying text in the <pre>
tag.
💡 To output code, you need to additionally wrap the contents of the <pre>
tag in the <code>
tag to emphasize that it contains code, rather than a schematic cat or a poem.
💡 When demonstrating HTML code within a <pre>
tag, there may be issues with displaying tags in angle brackets — the browser will interpret them as actual tags. To solve this problem, use mnemonic substitutions:
<
(less than) for the left angle bracket;>
(greater than) for the right angle bracket.
<pre><code> <div>Some text</div></code></pre>
<pre><code> <div>Some text</div> </code></pre>
💡 Collapsing spaces and line breaks outside the <pre>
tag can also be avoided using CSS, specifically the property white
.
💡 Too long lines may extend beyond the <pre>
tag; to solve this issue, use CSS, specifically adding scrolling – overflow
, or line wrapping – white
.