🔰syntax highlighting
dev ⟩ tools ⟩ syntax highlighting
- ChatGPT ⟩ 語法高亮實現方法 
多餘的空白❗
使用下方介紹的 JavaScript 函式庫時,如果 <pre><code> 的寫法如下:
<pre><code class="language-javascript">
function greet(name) {
    console.log(`Hello, ${name}!`);
}
greet("World");
</code></pre>呈現出來的樣子像這樣:

網頁上方會出現一個多餘的空白區,這是因為 <pre> 會「保留所有的換行和空白」,包含 <pre><code> 後面的換行,因此在網頁上會呈現一行空白。
💊 解決方法
手動調整:在 <pre><code> 後面接著打,別直接換行。
<pre><code class="language-javascript">function greet(name) {
    console.log(`Hello, ${name}!`);
}
greet("World");
</code></pre>使用 CSS ⟩ white-space 自動調整樣式
pre {
    /* 保留換行,但去除多餘空白 */
    white-space: pre-wrap; 
}實現方法
📁 html
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.js"></script>
</head>
<body>
<pre><code class="language-javascript">function greet(name) {
    console.log(`Hello, ${name}!`);
}
greet("World");
</code></pre>
</body>📁 html
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/default.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
</head>
<pre><code class="javascript">function greet(name) {
    console.log(`Hello, ${name}!`);
}
greet("World");
</code></pre>Last updated
Was this helpful?