counter() CSS function returns a string representing the current value of the named counter, if there is one. It is generally used with pseudo-elements , but can be used, theoretically, anywhere a <string> value is supported.

/* Simple usage */
counter(countername);
/* changing the counter display */
counter(countername, upper-roman)
					

A counter has no visible effect by itself. The counter() function (and counters() function) is what makes it useful by returning developer defined strings (or images).

注意: counter() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse.

检查 浏览器兼容性表格 要小心谨慎在生产中使用这之前。

句法

<custom-ident>
A name identifying the counter, which is the same case-sensitive name used for the counter-reset and counter-increment . The name cannot start with two dashes and can't be none , unset , initial ,或 inherit .
<counter-style>
A <list-style-type> name, <@counter-style> name or symbols() function, where a counter style name is a numeric , alphabetic ,或 symbolic simple predefined counter style, a complex longhand east Asian or Ethiopic predefined counter style, or other predefined counter style . If omitted, the counter-style defaults to decimal .

形式句法

counter( <custom-ident>, <counter-style>? )

where
<counter-style> = <counter-style-name> | symbols()

where
<counter-style-name> = <custom-ident>

范例

default value compared to upper Roman

HTML

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

CSS

ol {
  counter-reset: listCounter;
}
li {
  counter-increment: listCounter;
}
li::after {
  content: "[" counter(listCounter) "] == ["
               counter(listCounter, upper-roman) "]";
}
					

结果

decimal-leading-zero compared to 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, decimal-leading-zero) "] == ["
               counter(count, lower-alpha) "]";
}
					

结果

规范

规范 状态 注释
CSS Lists Module Level 3
The definition of 'CSS Counters' in that specification.
工作草案 No change
CSS Level 2 (Revision 1)
The definition of 'CSS Counters' in that specification.
推荐 初始定义

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
counter() Chrome 完整支持 1 Edge 完整支持 12 Firefox 完整支持 1 IE 完整支持 8 Opera 完整支持 9.2 Safari 完整支持 3 WebView Android 完整支持 ≤37 Chrome Android 完整支持 18 Firefox Android 完整支持 4 Opera Android 完整支持 10.1 Safari iOS 完整支持 1 Samsung Internet Android 完整支持 1.0

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改:
  1. CSS
  2. CSS 参考