HTML 註解讓開發者在原始碼留下說明、暫時停用代碼、標記區塊邊界,且不會在瀏覽器畫面顯示。正確使用註解能提升代碼可讀性與團隊協作效率,但也有巢狀限制與舊版 IE 條件註解等特殊規則需注意。
<!-- 這是單行註解 -->
<!--
這是多行註解
可以跨越多行
結束標記不需在同一行
-->
<!-- <p>這段 HTML 暫時停用</p> -->
核心規則:
| 語言 | 單行註解 | 多行註解 | 可巢狀 |
|---|---|---|---|
| HTML | <!-- 註解 --> | <!-- 多行 --> | 否 |
| CSS | 無 | /* 註解 */ | 否(標準),支援 /* /* 巢狀 */ */(CSS 模組規範) |
| JavaScript | // 註解 | /* 註解 */ | 否 |
IE 5–9 支援的專屬機制,其他瀏覽器視為普通註解忽略:
<!--[if IE]>
<link rel="stylesheet" href="ie-fix.css">
<![endif]-->
<!--[if lt IE 9]>
<script src="html5shiv.js"></script>
<![endif]-->
<!--[if !IE]>> <!-- 非 IE 瀏覽器才會解析 -->
<link rel="stylesheet" href="modern.css">
<!--<![endif]-->
常見條件運算子:`IE` (所有 IE)、`lt` (小於)、`lte` (小於等於)、`gt` (大於)、`gte` (大於等於)、`!` (非)、`()` (分組)、`&` (且)、`|` (或)、`true`/`false` (常真/常假)。
⚠️ **IE10+ 已移除條件註解支援**,現代專案請改用特性偵測、Polyfill、漸進增強策略。
<header class="site-header">
<!-- BEGIN: Header -->
...
<!-- END: Header -->
</header>
<main class="site-main">
<!-- BEGIN: Main Content -->
...
<!-- END: Main Content -->
</main>
<!--
<section class="promo-banner">
<h2>限時優惠</h2>
</section>
-->
<!-- @section('content') -->
<!-- @endsection -->
<!-- {{-- Blade 註解:不會輸出到 HTML --}} -->
<!-- inject:css -->
<!-- endinject -->
<!-- vite:legacy -->
<!-- endvite -->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "文章標題"
<!-- "author": { "@type": "Person", "name": "作者" } -->
}
</script>
// vite.config.js
export default {
build: {
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
},
format: {
comments: false // 移除所有註解
}
}
}
}
// 或使用 html-minifier-terser 專門處理 HTML
// npm install html-minifier-terser
const { minify } = require('html-minifier-terser');
const result = await minify(html, { removeComments: true, collapseWhitespace: true });
善用 HTML 註解讓代碼自文件化,但切記:好代碼勝過好註解,清晰的命名與結構才是王道。定期清理過期註解,保持代碼庫整潔專業。