CSS counter() Function

Definition and Usage

counter() Functions return the current value of the specified counter as a string.

Example

Example 1

Create a counter for the page (in the body selector). Increase the counter value for each <h2> element and add the text "Chapter X" before each <h2> element:

body {
  counter-reset: section;
}
h2::before {
  counter-increment: section;
  content: "Section " counter(section) ": ";
}

Try It Yourself

Example 2

Set the counter style:

body {
  counter-reset: section;
}
h2::before {
  counter-increment: section;
  content: "Section " counter(section, upper-roman) ": ";
}

Try It Yourself

CSS Syntax

counter(countername, counterstyle)
Value Description
countername

Required. The name of the counter (the same as the name used in the counter-reset and counter-increment attributes).

Note, names are case-sensitive.

counterstyle

Optional. The counter style (can be the value of list-style-type, @counter-style name, or symbols() function).

The default value is decimal.

Technical Details

Version: CSS3

Browser Support

Chrome Edge Firefox Safari Opera
支持 支持 支持 支持 支持

相关页面

教程:CSS 计数器

参考:CSS content 属性

参考:CSS counter-increment 属性

参考:CSS counter-reset 属性

参考:CSS @counter-style 规则

参考:CSS counters() 函数