<pre> (Preformatted Text) 保留原始碼中的空白、換行、縮排、Tab,以等寬字體顯示。是展示程式碼、ASCII 藝術、日誌、詩歌、終端機輸出的標準標籤。
<pre><code class="language-js">function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('World');</code></pre>
<code> 表語意「程式碼」,配合高亮套件 (Prism, Highlight.js, Shiki) 實現語法著色<pre> 預設 white-space: pre、font-family: monospace| 值 | 換行 | 空白合併 | 文字換行 | 適用場景 |
|---|---|---|---|---|
normal | 否 | 是 | 是 | 一般文字 (預設) |
nowrap | 否 | 是 | 否 | 單行截斷配合 text-overflow: ellipsis |
pre | 是 | 否 | 否 | <pre>、程式碼、ASCII 藝術 |
pre-wrap | 是 | 否 | 是 | 保留格式但超寬自動換行 (常用於日誌、Markdown 渲染) |
pre-line | 是 | 是 | 是 | 保留換行、合併空白 (類似純文字編輯器) |
break-spaces | 是 | 否 | 是 | 同 pre-wrap 但保留末尾空白、允許在空白處斷行 (CSS3) |
pre { overflow-x: auto; max-width: 100%; }
pre { tab-size: 2; /* 或 4,預設 8 */ }
navigator.clipboard.writeText(pre.innerText)code:not(pre code) { white-space: nowrap; }<pre><code> 結構讓螢幕閱讀器識別為程式碼區塊,可跳過逐字朗讀<pre> 內容的純文字替代說明 (複雜 ASCII 圖表)<textarea class="code-editor" spellcheck="false">const x = 1;</textarea>
<style>
.code-editor {
font-family: inherit; font-size: inherit; line-height: inherit;
tab-size: 2; white-space: pre; /* textarea 預設 pre-wrap */
border: 1px solid #ccc; border-radius: 4px; padding: 0.5rem;
width: 100%; min-height: 200px; resize: vertical;
}
</style>