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

示例

再來看另一個示例,此示例展示如何使用 CSS 在 HTML 中的 <pre> 標籤內建立帶有固定寬度的預格式化的文字 -

<!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.