CSS Counter(counter-reset、counter-increment、counter()/counters())自 CSS2 起支援,配合 ::before/::after 可在無腳本情況下為標題、列表、表格、程式碼區塊自動生成序號。
body {
counter-reset: heading; /* 初始化計數器 */
}
h2::before {
counter-increment: heading; /* 遞增 */
content: "Section " counter(heading) ". "; /* 顯示 */
}
article {
counter-reset: section;
}
section {
counter-reset: subsection;
}
section h2::before {
counter-increment: section;
content: counter(section) ". ";
}
section section h3::before {
counter-increment: subsection;
content: counter(section) "." counter(subsection) " "; /* 1.1, 1.2... */
}
或使用 counters() 簡化:
section h3::before {
content: counters(section, ".") " "; /* 自動處理巢狀層級 */
}
pre { counter-reset: line; } code::before { counter-increment: line; content: counter(line); }figure::before { counter-increment: fig; content: "Figure " counter(fig) ": "; }counters() 產生 1.1.1 (a) 格式。@page { counter-increment: page; } @bottom-center { content: counter(page); }display: none 的元素不會遞增計數器(visibility: hidden 會)。CSS Counter 讓內容結構與呈現分離,文檔增刪修改自動同步編號,是技術文檔、部落格、電商規格書的利器。