萬盛學電腦網

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

CSS counter() 自動編號:突破 <ol> 限制的靈活編號方案

核心三步驟

  1. counter-reset: 名稱 —— 在容器建立/重置計數器。
  2. counter-increment: 名稱 —— 在目標元素遞增。
  3. content: counter(名稱) —— 在偽元素顯示。

基本範例:標題自動編號

body { counter-reset: h2-counter; }
h2::before {
  counter-increment: h2-counter;
  content: "第 " counter(h2-counter) " 章 ";
  margin-right: 0.5em;
  color: #0066cc;
}

多層級嵌套編號(如 1.1、1.2、2.1)

article { counter-reset: section; }
h2 { counter-reset: subsection; } /* 子計數器隨父重置 */
h2::before {
  counter-increment: section;
  content: counter(section) " ";
}
h3::before {
  counter-increment: subsection;
  content: counter(section) "." counter(subsection) " ";
}

自定義編號格式

counter(name, upper-roman)    /* I, II, III */
counter(name, lower-alpha)    /* a, b, c */
counter(name, cjk-ideographic) /* 一, 二, 三 */
counter(name, "★ ")           /* 自定義字串(CSS3) */

實用場景

  • 文檔大綱自動編號(不依賴 <ol> 結構)。
  • 圖表/代碼區塊編號:figure::before { content: "圖 " counter(fig) ":" }
  • 分頁列表項號、法律條文編號。

瀏覽器支援

IE8+、所有現代瀏覽器完整支援。無需前綴。

copyright © 萬盛學電腦網 all rights reserved