HTML <pre> Element

Publish in HTML Tutorial el 25/05/2025 14:59

The HTML <pre> Element: Preserving Text Formatting

The <pre> element in HTML defines preformatted text. Text within a <pre> element is displayed exactly as written in the HTML source code - preserving both spaces and line breaks. This makes it ideal for displaying code blocks, ASCII art, or any content where whitespace matters.


Key Characteristics:

  • Monospaced font (typically Courier or similar)
  • Preserves all whitespace (spaces, tabs, line breaks)
  • Does not automatically wrap text (unless CSS is applied)
  • Often used with <code> element for code blocks


Basic Syntax:


Basic Example

Here's a simple example showing how the pre element preserves formatting:

Play Code


Displaying Code with Syntax Highlighting

While <pre> preserves formatting, you can combine it with <code> for better semantic meaning:

Play Code


ASCII Art Example

The <pre> element is perfect for displaying ASCII art:

Play Code


Dynamic Content with JavaScript

You can update the content of a <pre> element dynamically with JavaScript:

Play Code


Logging Output with JavaScript

Here's how you can use <pre> to display console-like output:

Play Code


Tips and Tricks

  • Horizontal Scrolling: By default, <pre> elements don't wrap text. Add white-space: pre-wrap; in CSS to enable wrapping.
  • Syntax Highlighting: Combine with libraries like Prism.js or Highlight.js for beautiful code display.
  • Accessibility: Add appropriate ARIA roles when displaying code (role="code").
  • Tab Size: Control tab width with CSS tab-size property.
  • Line Numbers: Add line numbers by combining with CSS counters.


CSS Styling Example

También te puede interesar

HTML <style> Element
HTML <style> Element

The <style> HTML element contains style information for a document, or part of a document. ...

HTML <strong> Element
HTML <strong> Element

The <strong> element is used to indicate that its content has strong importance, seriousnes...

HTML <span> Element
HTML <span> Element

The <span> element is an inline container used to mark up a part of a text or document. Unl...

HTML <source> Element
HTML <source> Element

The <source> element is used to specify multiple media resources for media elements like &l...

HTML <small> Element
HTML <small> Element

The <small> element is used to represent side-comments and small print, typically for discl...

HTML <section> Element
HTML <section> Element

HTML <section> Element: The Complete Guide The <section> element is a semantic HTML ...