如何向 HTML 中添加预格式化文本?


在 HTML 中,<pre> 标签用于预格式化文本。处于 <pre> 开头和闭合 </pre> 标签之间的文本与在 HTML 文档中编写的文本内容完全相同。预格式化文本的用法如下所示 -

<pre> ---- </pre>

<pre> 元素以保留空格和换行符的形式显示文本,并以等宽字体表示。

示例

以下示例尝试在 HTML 中添加预格式化文本 −

<!DOCTYPE html>
<html>
<body>
   <h2> Different variations on Displaying Paragraph</h2>
   <pre>The <b>pre</b> element displayed the text with preserved space and line breaks and also represents in a fixed-width font.</pre>
</body>
</html>

将 CSS 设置应用于 HTML 中的 <pre> 标签

处于 <pre> 元素之间的文本以等宽字体显示;可以通过使用 CSS 来更改它。

示例

以下为另一个示例,我们可以在其中向 HTML 中添加预格式化文本 −

<html>
<head>
   <title>Applying CSS to pre tag in HTML</title>
   <style>
      pre {
         font-family: Lucida Handwriting;
         color: blue;
         margin: 30px;
      }
   </style>
</head>
<body>
   <pre>
        Tutorials Point is a leading Ed Tech company striving to provide the best learning material on technical and non-technical subjects.
     </pre>
</body>
</html>

示例

考虑 HTML 中 <pre> 标签的另一个示例,它使用 CSS 创建具有固定宽度的预格式化文本 -

<!DOCTYPE html>
<html>
<body>
   <h2>Usage of standard pre tag</h2>
   <pre>The standard pre tag uses as much space as it needs.</pre>
   <h2>Usage of Fixed width pre</h2>
   <div style="width:150px;overflow:auto">
      <pre>A pre tag with a fixed width. It uses as much space as specified.</pre>
   </div>
</body>
</html>

示例

<!DOCTYPE html>
<html>
<head>
   <style>
      pre {
         display: block;
         font-family: monospace;
         color: blue;
         white-space: pre;
         margin: 1em 0;
      }

      h2 {
         color: red;
      }
   </style>
</head>
<body>
   <h2>Usage of standard pre tag</h2>
   <pre>The standard pre tag uses as much space as it needs.</pre>
   <h3>Usage of Fixed width pre</h3>
   <div style="width:150px;overflow:auto">
      <pre>A pre tag with a fixed width. It uses as much space as specified.</pre>
   </div>
</body>
</html>

更新时间:2023 年 10 月 10 日

593 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.