<pre>:預格式化文本元素

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

<pre> HTML 元素表示預格式化文本,將以 HTML 檔案中的原樣呈現。這段文字通常使用非比例或等寬字體進行渲染。該元素內的空格會按照原樣呈現。

預設情況下,<pre>區塊級元素,即其預設的 display 值為 block

嘗試一下

如果你需要在 <pre> 標籤內顯示保留字元,如 <>&",這些字元必須使用相應的 HTML 實體進行轉義。

屬性

此元素僅包括全域屬性

cols Non-standard 已棄用

包含應有的行數的首選字元數。這是 width 的非標準同義詞。要實現此效果,請改用 CSS width

width 已棄用 Non-standard

包含應有的行數的首選字元數。儘管在技術上仍有實現,但此屬性無視視覺效果;要實現此效果,請改用 CSS width

wrap Non-standard 已棄用

是一個指示溢出應發生的提示。在現代瀏覽器中,此提示會被忽略且不會有視覺效果;要實現此效果,請改用 CSS white-space

可及性考量

對於使用預格式化文本創建的任何圖片或圖表,提供替代描述是重要的。替代描述應清晰簡明地描述圖片或圖表的內容。

使用輔助技術(如屏幕閱讀器)瀏覽的視覺受損人士可能無法理解預格式化文本字符在順序讀出時代表什麼。

<figure><figcaption> 元素的組合,再加上 pre 元素上的 ARIA rolearia-label 屬性,允許預格式化的 ASCII 藝術被宣告為帶有替代文本的圖片,figcaption 則作為圖片的標題。

範例

html
<figure>
  <pre role="img" aria-label="ASCII COW">
      ___________________________
  &lt; I'm an expert in my field. &gt;
      ---------------------------
          \   ^__^
           \  (oo)\_______
              (__)\       )\/\
                  ||----w |
                  ||     ||
  </pre>
  <figcaption id="cow-caption">
    A cow saying, "I'm an expert in my field." The cow is illustrated using
    preformatted text characters.
  </figcaption>
</figure>

範例

基本範例

HTML

html
<p>Using CSS to change the font color is easy.</p>
<pre>
body {
  color: red;
}
</pre>

結果

轉義保留字元

HTML

html
<pre>
let i = 5;

if (i &lt; 10 &amp;&amp; i &gt; 0)
  return &quot;Single Digit Number&quot;
</pre>

結果

技術摘要

內容類型 流內容、捫及內容。
允許內容 段落型內容
標籤省略 不允許,開始和結束標籤都是必須的。
允許的父元素 任何接受流內容的元素。
隱含 ARIA 角色 generic
允許的 ARIA 角色 任何
DOM 介面 HTMLPreElement

規範

Specification
HTML
# the-pre-element

瀏覽器相容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
pre
width
DeprecatedNon-standard
wrap
DeprecatedNon-standard

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Non-standard. Check cross-browser support before using.
Deprecated. Not for use in new websites.
See implementation notes.

參見