跳至主要内容

[CSS] Custom Counter

keywords: 計數器, ol

CSS Counter (計數器)可以客制化一些計數時的樣式,經常用在清單中,特別像是 ordered list 的情況。

設定初始值

要使用 CSS 計數器,必須要先透過 counter-reset 來給予初始化的值,預設是 0。

/**
* 初始化一個計數器,並給予名稱(這裡叫做 section),預設是 0
**/
div {
counter-reset: section;
}

顯示計數值

計數器初始化後,可以透過 counter-increment 來增加或減少計數器的值。

計數器值的顯示可以透過在偽元素的 content 屬性中使用 counter()counters() 的函式:

  • counter():counter(name), counter(name, style)
  • counters(): counters(name, string), counters(name, string, style)

其中,style 指的是 CSS 中的 list-style

h3::before {
counter-increment: section; // 遞增計數器 section 的值
content: counter(section); // 顯示計數器 section 的值
}

li::before {
counter-increment: nested;
content: counters(nested, '.') ' ';
}

li::before {
counter-increment: list;
content: counter(list, upper-roman) '.';
}

程式範例

See the Pen [CSS] Counter by PJCHEN (@PJCHENder) on CodePen.

參考