阿里云主机折上折
  • 微信号
Current Site:Index > The preformatted text tag (pre) translates this sentence into English, outputting plain text directly without any additional content.

The preformatted text tag (pre) translates this sentence into English, outputting plain text directly without any additional content.

Author:Chuan Chen 阅读数:47778人阅读 分类: HTML

The <pre> tag in HTML is used to define preformatted text. Browsers preserve the original formatting of the text within this tag, including spaces, line breaks, and indentation, typically displayed in a monospace font. This stands in stark contrast to HTML's default behavior of ignoring extra spaces and line breaks.

<pre>
  This text
    will preserve
      all spaces and line breaks
</pre>

Basic Characteristics

The most notable feature of the <pre> element is its preservation of the original text layout. In regular HTML, consecutive spaces and line breaks are compressed into a single space:

<p>These   spaces and
  line breaks
  will be ignored</p>

Whereas with <pre>:

<pre>These   spaces and
  line breaks
  will be preserved</pre>

By default, <pre> content will:

  • Use a monospace font (typically Courier New)
  • Preserve all whitespace characters
  • Not wrap automatically (may result in horizontal scrollbars)

Relationship with the <code> Tag

<pre> is often used in combination with <code> to display code snippets:

<pre><code>
function hello() {
  console.log("Hello World!");
  return true;
}
</code></pre>

This combination preserves code formatting while semantically indicating that it is code content. In modern development, this pattern is widely used in technical documentation and tutorials.

Style Control

Although <pre> has default styling, it can be fully customized with CSS:

pre {
  background-color: #f4f4f4;
  border-left: 3px solid #3498db;
  font-family: 'Consolas', monospace;
  line-height: 1.6;
  margin: 1.5em 0;
  overflow: auto;
  padding: 1em;
  display: block;
  white-space: pre-wrap; /* Allows automatic line wrapping */
}

The white-space property is particularly important, with several options:

  • pre: Fully preserves whitespace (default)
  • pre-wrap: Preserves whitespace but allows line breaks
  • pre-line: Merges whitespace but preserves line breaks

Practical Use Cases

  1. Code Display:
<pre><code class="language-javascript">
// Binary search algorithm
function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;
  
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  
  return -1;
}
</code></pre>
  1. ASCII Art:
<pre>
  /\_/\
 ( o.o )
  > ^ <
</pre>
  1. Formatted Text:
<pre>
Recipient: John Doe
Subject: Meeting Notice
Date: 2023-11-15

Please attend the project review meeting this Friday at 2 PM.
Location: Conference Room A, 3rd Floor.
</pre>

Advanced Usage

Combining with JavaScript enables dynamic content:

<pre id="dynamic-pre"></pre>

<script>
  const preElement = document.getElementById('dynamic-pre');
  const data = {
    user: 'Alice',
    level: 'admin',
    lastLogin: '2023-11-10T08:30:00Z'
  };
  
  preElement.textContent = JSON.stringify(data, null, 2);
</script>

Output effect:

{
  "user": "Alice",
  "level": "admin",
  "lastLogin": "2023-11-10T08:30:00Z"
}

Accessibility Considerations

Provide appropriate descriptions for <pre> content:

<div role="region" aria-labelledby="code-heading">
  <h3 id="code-heading">JavaScript Example Code</h3>
  <pre><code>
  // Code here
  </code></pre>
</div>

For complex content, consider adding "skip" links or providing alternative text.

Performance Impact

Large <pre> content may affect page performance:

  • Very long lines may cause layout issues
  • Excessive content increases DOM size
  • Syntax highlighting may cause rendering delays

Solutions:

// Lazy loading example
const preObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      loadPreContent(entry.target);
      preObserver.unobserve(entry.target);
    }
  });
});

document.querySelectorAll('pre.lazy').forEach(pre => {
  preObserver.observe(pre);
});

Integration with Other Technologies

  1. Markdown Conversion: Many Markdown parsers convert code blocks into <pre><code> combinations.

  2. Syntax Highlighting: Using libraries like Prism.js or highlight.js:

<pre><code class="language-javascript">
// Highlight example
const message = "Hello World";
console.log(message);
</code></pre>

<!-- Include highlighting library -->
<script src="prism.js"></script>
  1. Terminal Simulation: Creating command-line interface effects:
.terminal {
  background-color: #000;
  color: #0f0;
  padding: 1em;
  border-radius: 5px;
  font-family: monospace;
}
<pre class="terminal">
$ npm install package
Installing...
Package installed successfully!
</pre>

Browser Compatibility

The <pre> tag is well-supported in all modern browsers, including:

  • Chrome 1+
  • Firefox 1+
  • Safari 1+
  • Edge 12+
  • Opera 7+

Notable differences:

  • Early IE versions handle tab characters inconsistently
  • Mobile browsers may adjust default font sizes
  • Print styles may require special handling

Content Security

When displaying user-provided content:

// Safe handling
function safePreContent(text) {
  return text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

userContent = safePreContent(userInput);
preElement.innerHTML = userContent;

Responsive Design

Ensure <pre> behaves well across devices:

@media screen and (max-width: 600px) {
  pre {
    font-size: 14px;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    white-space: pre-wrap;
    word-wrap: break-word;
  }
}

Print Optimization

Style adjustments for print media:

@media print {
  pre {
    page-break-inside: avoid;
    background-color: #fff !important;
    color: #000 !important;
    border: 1px solid #ddd !important;
  }
}

Nesting Rules

The <pre> tag can contain:

  • Text content
  • Phrase elements (<strong>, <em>, etc.)
  • Code-related elements like <code>, <samp>, <kbd>

But cannot contain:

  • Block-level elements (<div>, <p>, etc.)
  • Elements that disrupt formatting (<br>, <img>, etc.)

Historical Evolution

The definition of <pre> in HTML specifications has undergone several changes:

  • HTML 2.0: Basic preformatting functionality
  • HTML 4.01: Added width attribute (now deprecated)
  • HTML5: Clarified content model and semantic role
  • Modern HTML: Integrated with ARIA roles

Alternative Comparisons

  1. Read-only <textarea>:
<textarea readonly style="font-family: monospace; border: none; background: #f5f5f5;">
  Content here
  also preserves formatting
</textarea>
  1. CSS white-space Property:
<div style="white-space: pre-wrap; font-family: monospace;">
  Simulating pre effect with CSS
</div>
  1. <xmp> Tag (deprecated):
<xmp>
  Old-style preformatting tag
  Not recommended
</xmp>

Debugging Tips

When troubleshooting <pre> elements:

  1. Confirm no accidental style inheritance
  2. Check special character encoding
  3. Verify correct DOM structure
  4. Test display effects with different fonts
// Get computed styles
const preStyle = window.getComputedStyle(document.querySelector('pre'));
console.log(preStyle.whiteSpace);
console.log(preStyle.fontFamily);

Server-Side Processing

When generating <pre> content server-side:

  • Properly escape HTML special characters
  • Handle different OS line endings (\n vs \r\n)
  • Consider content encoding (UTF-8 recommended)

PHP example:

<?php
$code = '<?php echo "Hello World!"; ?>';
echo '<pre>' . htmlspecialchars($code) . '</pre>';
?>

Content Editing

Making <pre> editable:

<pre contenteditable="true" style="outline: none;">
  Click to edit this text
  While preserving preformatting
</pre>

Saving changes with JavaScript:

document.querySelector('pre[contenteditable]').addEventListener('blur', function() {
  localStorage.setItem('preContent', this.textContent);
});

Extended Applications

  1. Data Visualization:
const data = [12, 19, 3, 5, 2, 3];
const pre = document.createElement('pre');
pre.textContent = data.map(val => '■'.repeat(val)).join('\n');
document.body.appendChild(pre);
  1. Text Games:
<pre id="game">
  ########
  #      #
  # @    #
  #      #
  ########
</pre>

<script>
  // Simple keyboard control logic
  document.addEventListener('keydown', (e) => {
    const game = document.getElementById('game');
    let content = game.textContent;
    // Handle movement logic...
    game.textContent = updatedContent;
  });
</script>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.