<pre> element is used to display preformatted text. Within the
<pre> tag, the text retains its original structure, preserving whitespace characteristics like spaces and newlines. This behavior is often beneficial for displaying code or other text where spacing and line breaks are crucial. Additionally, when displayed in a browser, the content inside the element typically utilizes a monospaced font, ensuring consistent width for each character.
Examples and Usage
To showcase the element's capability in preserving whitespace and layout, consider the ASCII representation of a cactus plant:
<pre> ,*-. | | ,. | | | |_| | ,. `---. |_| | | .--` | | | | </pre>
,*-. | | ,. | | | |_| | ,. `---. |_| | | .--` | | | |
The depiction we demonstrated above highlights the element's ability to retain whitespace and line breaks, making it perfect for textual representations like ASCII art.
In a more practical context,
<pre> can be paired with the
<code> tag to present code snippets:
As we can see, the indentation and line breaks of the code are preserved, while the
<code> element semantically indicates computer code. The pairing provides a clear and organized representation of code on web pages.
<pre> element can utilize the global attributes applicable to all HTML elements. Certain non-standard and deprecated attributes, such as
wrap, which once impacted the element's behavior, are no longer recommended. Modern styling techniques using CSS are preferred for controlling appearance and behavior.
<pre> element for ASCII art or diagrams requires alternative descriptions. ASCII art, created from characters, can be confusing when interpreted by screen readers, potentially making the representation ambiguous for visually impaired users. To address this, wrapping the
<pre> element with the
<figure> element and providing a
<figcaption> offers contextual understanding. ARIA (Accessible Rich Internet Applications) attributes, such as
aria-label, can be added to further specify the content's nature and purpose, making sure that assistive technologies can interpret and announce the content more effectively.
HTML Entities allow for the representation of characters reserved in HTML, such as
>. They come in handy within the
<pre> element to showcase reserved characters. For instance:
Where the output would be:
The approach provides a way to safely display reserved characters in HTML without them being interpreted by the browser.
Further considerations include:
CSS properties such as
word-breakcan be used to modify how text wraps or how whitespace behaves within elements like
While monospaced fonts are commonly associated with the
<pre>element, developers have the liberty to style it differently using CSS, tailoring the look and feel to their requirements.
For a detailed breakdown of specific browser nuances and older version support refer to the first link in the Useful Resources below.