萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS Counter 計數器實戰:自動編號標題、列表與巢狀結構

告別手動維護序號:CSS Counter 讓文檔結構自動編號

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 會)。
  • IE8+ 完整支援,現代瀏覽器無憂慮。

CSS Counter 讓內容結構與呈現分離,文檔增刪修改自動同步編號,是技術文檔、部落格、電商規格書的利器。

copyright © 萬盛學電腦網 all rights reserved