CSS - counter() 函数



CSS 的counter()函数返回一个字符串,显示指定命名计数器的当前值。通常,它用于content属性中,搭配伪元素使用。

可能的参数值

  • <counter-name> − 这是计数器的唯一名称,必须与counter-resetcounter-increment中使用的名称大小写完全一致。名称不能以两个连字符开头,也不能是 none、unset、initial 或 inherit。

  • <counter-style> − 此参数可选。计数器的样式(可以是list-style-type值或@counter-style值或symbols()函数)。计数器样式的名称可以很简单,例如数字、字母或符号等。

语法

counter(<countername>, <counterstyle>)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

CSS counter() - 基本示例

这是一个演示counter()函数的示例。

Open Compiler
<html> <head> <style> .demo-counter { counter-reset: item-counter; } .demo-counter li { list-style-type: none; counter-increment: item-counter; } .demo-counter li::before { content: counter(item-counter) ". "; } </style> </head> <body> <ul class="demo-counter"> <li>First item</li> <li>Second item</li> <li>Third item</li> <li>Fourth item</li> <li>Fifth item</li> </ul> </body> </html>

CSS counter() - 使用两种样式

此程序演示了使用counter()函数和两种不同计数器样式的方法。

Open Compiler
<html> <head> <style> ul { counter-reset: demo-counter; list-style: none; margin: 10px; padding: 10px; } li { counter-increment: demo-counter; margin-bottom: 1em; } li::before { content: "[" counter(demo-counter) "] "; font-weight: bold; color: #3498db; } li::after { content: " (Level " counter(demo-counter, lower-roman) ")"; font-style: italic; color: #e74c3c; } </style> </head> <body> <ul> <li>This is the first item</li> <li>This is the second item</li> <li>This is the third item</li> <li>This is the fourth item</li> <li>And this is fifth and last item</li> </ul> </body> </html>
广告