CSS 計數器

CSS 計數器通過一個變數來設定,根據規則遞增變數。


使用計數器自動編號

CSS 計數器根據規則來遞增變數。

CSS 計數器使用到以下幾個屬性:

  • counter-reset - 建立或者重置計數器
  • counter-increment - 遞增變數
  • content - 插入生成的內容
  • counter()counters() 函式 - 將計數器的值新增到元素

要使用 CSS 計數器,得先用 counter-reset 建立:

以下例項在頁面建立一個計數器 (在 body 選擇器中),每個 <h2> 元素的計數值都會遞增,並在每個 <h2> 元素前新增 "Section <計數值>:"

CSS 例項

body { counter-reset: section; } h2::before { counter-increment: section; content: "Section " counter(section) ": "; }

嘗試一下 ?

巢狀計數器

以下例項在頁面建立一個計數器,在每一個 <h1> 元素前新增計數值 "Section <主標題計數值>.", 巢狀的計數值則放在 <h2> 元素的前面,內容為 "<主標題計數值>.<副標題計數值>":

CSS 例項

body { counter-reset: section; } h1 { counter-reset: subsection; } h1::before { counter-increment: section; content: "Section " counter(section) ". "; } h2::before { counter-increment: subsection; content: counter(section) "." counter(subsection) " "; }

嘗試一下 ?

計數器也可用於列表中,列表的子元素會自動建立。這裡我們使用了 counters() 函式在不同的巢狀層級中插入字串:

CSS 例項

ol { counter-reset: section; list-style-type: none; } li::before { counter-increment: section; content: counters(section,".") " "; }

嘗試一下 ?

CSS 計數器屬性

屬性 描述
content 使用 ::before 和 ::after 偽元素來插入自動生成的內容
counter-increment 遞增一個或多個值
counter-reset 建立或重置一個或多個計數器