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 | 創建或重置一個或多個計數器 |