<pre>

HTML <pre> 元素表示预定义格式文本。在该元素中的文本通常按照原文件中的编排,以等宽字体的形式展现出来,文本中的空白符(比如空格和换行符)都会显示出来。(紧跟在 <pre> 开始标签后的换行符也会被省略)

尝试一下

备注: 你需要将该元素里的 '<' 字符转义为 '&lt;' 以保证代码里的关闭代码不被浏览器解释为标签。

内容类别 流内容 ( flow content) , 可触知的内容 (palpable content).
允许的 内容 Phrasing content.
省略标签 不允许,开始标签和结束标签都不能省略。
允许的 父元素 任何可以接受流内容 ( flow content) 的元素
允许的 ARIA 角色 任何
DOM 接口 HTMLPreElement (en-US)

属性

这个元素只具有全局属性。

cols 非标准 已弃用

定义每行的最大字符数。这是一个非标准的属性,作用与width相同。要实现这样的效果,应该使用 CSS。

width 已弃用

包含每行的最大字符数。虽然在技术上仍被实现,但这个属性没有视觉效果。要实现这样的效果,应该使用 CSS。

wrap 非标准

提示溢出怎样发生。在现代浏览器中,这个提示会被忽略,且被没有视觉效果。要实现这样的效果,应该使用 CSS。

示例

HTML

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

结果

无障碍

It is important to provide an alternate description for any images or diagrams created using preformatted text. The alternate description should clearly and concisely describe the image or diagram's content.

People experiencing low vision conditions and browsing with the aid of assistive technology such as a screen reader may not understand what the preformatted text characters are representing when they are read out in sequence.

A combination of the <figure> and <figcaption> elements, supplemented by a combination of an id and the ARIA role and aria-labelledby attributes allow the preformatted text to be announced as an image, with the figcaption serving as the image's alternate description.

示例

<figure role="img" aria-labelledby="cow-caption">
  <pre>
  ___________________________
< I'm an expert in my field. >
  ---------------------------
         \   ^__^
          \  (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>

规范

Specification
HTML Standard
# the-pre-element

浏览器兼容性

BCD tables only load in the browser

参见