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

htmlfront end technologyweb development更新于 2024/7/25 12:28:17

在 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>

相关文章


有用资源