counter()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

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>

语法

css
/* 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-resetcounter-increment 属性值使用的名称相同,区分大小写。计数器名称不能以两个破折号开头,也不能是 noneunsetinitialinherit

<counter-style>

一个 <list-style-type> 名称,<@counter-style> 名称或 symbols() 函数,其中计数器样式名称是 numericalphabeticsymbolic 预定义计数器样式,复杂的长格式东亚或埃塞俄比亚预定义计数器样式,或其他预定义计数器样式。如果省略,计数器样式默认为 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-romanlower-alpha 列表样式显示计数器。

HTML

html
<ol>
  <li></li>
  <li></li>
  <li></li>
</ol>

CSS

css
ol {
  counter-reset: count;
}
li {
  counter-increment: count;
}
li::after {
  content:
    "[" counter(count, lower-roman) "] == ["
    counter(count, lower-alpha) "]";
}

结果

使用三种样式显示计数器

在此示例中,我们使用了三次 counter() 函数。

HTML

html
<ol>
  <li></li>
  <li></li>
  <li></li>
</ol>

CSS

我们包含了 counter() 函数,带有三种不同的计数器样式,包括默认的十进制值。我们为列表添加了内边距,以便为长的 ::marker 字符串提供空间。

css
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

浏览器兼容性

另见