counter()
counter() CSS 函式返回一個字串,表示命名的計數器的當前值(如果存在)。
counter() 函式通常透過 content 屬性在偽元素中使用,但理論上,只要支援 <string> 值,它就可以在任何地方使用。
試一試
.double-list {
counter-reset: count -1;
}
.double-list li {
counter-increment: count 2;
}
.double-list li::marker {
content: counter(count, decimal) ") ";
}
<p>Best Dynamic Duos in Sports:</p>
<ol class="double-list">
<li>Simone Biles + Jonathan Owens</li>
<li>Serena Williams + Venus Williams</li>
<li>Aaron Judge + Giancarlo Stanton</li>
<li>LeBron James + Dwyane Wade</li>
<li>Xavi Hernandez + Andres Iniesta</li>
</ol>
語法
/* Basic usage */
counter(counter-name);
/* changing the counter display */
counter(counter-name, upper-roman)
計數器本身沒有可見效果。counter() 和 counters() 函式透過返回開發者定義的字串(或影像)使計數器變得有用。
值
counter() 函式最多接受兩個引數。第一個引數是 <counter-name>。可選的第二個引數是 <counter-style>。
<counter-name>-
一個
<custom-ident>,用於標識計數器,與counter-reset和counter-increment屬性值使用的名稱相同,區分大小寫。計數器名稱不能以兩個破折號開頭,也不能是none、unset、initial或inherit。 <counter-style>-
一個
<list-style-type>名稱,<@counter-style>名稱或symbols()函式,其中計數器樣式名稱是numeric、alphabetic或symbolic預定義計數器樣式,複雜的長格式東亞或衣索比亞預定義計數器樣式,或其他預定義計數器樣式。如果省略,計數器樣式預設為decimal。
注意:當巢狀計數器時,若要連線計數器值,請使用 counters() 函式,它提供了一個額外的 <string> 引數。
正式語法
<counter()> =
counter( <counter-name> , <counter-style>? )
<counter-style> =
<counter-style-name> |
<symbols()>
<symbols()> =
symbols( <symbols-type>? [ <string> | <image> ]+ )
<symbols-type> =
cyclic |
numeric |
alphabetic |
symbolic |
fixed
<image> =
<url> |
<image()> |
<image-set()> |
<cross-fade()> |
<element()> |
<gradient>
<image()> =
image( <image-tags>? [ <image-src>? , <color>? ]! )
<image-set()> =
image-set( <image-set-option># )
<cross-fade()> =
cross-fade( <cf-image># )
<element()> =
element( <id-selector> )
<image-tags> =
ltr |
rtl
<image-src> =
<url> |
<string>
<image-set-option> =
[ <image> | <string> ] [ <resolution> || type( <string> ) ]?
<cf-image> =
[ <image> | <color> ] &&
<percentage [0,100]>?
<id-selector> =
<hash-token>
示例
lower-roman 與 lower-alpha 的比較
在此示例中,我們使用 lower-roman 和 lower-alpha 列表樣式顯示計數器。
HTML
<ol>
<li></li>
<li></li>
<li></li>
</ol>
CSS
ol {
counter-reset: count;
}
li {
counter-increment: count;
}
li::after {
content:
"[" counter(count, lower-roman) "] == ["
counter(count, lower-alpha) "]";
}
結果
使用三種樣式顯示計數器
在此示例中,我們使用了三次 counter() 函式。
HTML
<ol>
<li></li>
<li></li>
<li></li>
</ol>
CSS
我們包含了 counter() 函式,帶有三種不同的計數器樣式,包括預設的十進位制值。我們為列表添加了內邊距,以便為長的 ::marker 字串提供空間。
ol {
counter-reset: listCounter;
padding-left: 5em;
}
li {
counter-increment: listCounter;
}
li::marker {
content:
"Item #" counter(listCounter) " is: ";
}
li::after {
content:
"[" counter(listCounter, decimal-leading-zero) "] == ["
counter(listCounter, upper-roman) "]";
}
結果
規範
| 規範 |
|---|
| CSS 列表與計數器模組第 3 級 # counter-functions |
| CSS Counter Styles Level 3 # 擴充套件 CSS2 |
瀏覽器相容性
載入中…