CSS counters() 函数



CSS 的 `counters()` 函数允许您使用嵌套计数器。它提供一个组合字符串,显示已命名的计数器的当前值(如果存在)。此函数有两种形式:

  • counters(name, string)

  • counters(name, string, style)

可以使用 `content` 属性显示计数器的值。

可能的值

  • `` − 这是计数器的唯一名称,必须与在 `counter-reset` 和 `counter-increment` 中使用的名称完全匹配大小写。名称不能以两个连字符开头,也不能为 none、unset、initial 或 inherit。

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

  • `` − 它使我们可以自由使用任意数量的文本字符。对于非拉丁字符,必须使用其 Unicode 转义序列表示。

    例如,`\000A9` 代表版权符号。

语法

counters( <custom-ident>, [, [ <counter-style> | none ] ], <string> )

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

CSS counters() - 基本示例

此程序演示了 `counters()` 函数的用法。

Open Compiler
<html> <style> ul { list-style: none; counter-reset: demo-counter; } ul li { counter-increment: demo-counter; background-color: lightgray; } ul li:before { content: counters(demo-counter, ".") " - "; color: red; } </style> <ul> <li>Chapter A <ul> <li>Unit- a <ul> <li>Sub-unit</li> <li>Sub-unit</li> </ul> </li> <li>Unit- b <ul> <li>Sub-unit</li> <li>Sub-unit</li> </ul> </li> </ul> </li> <li>Chapter B <ul> <li>Unit- a <ul> <li>Sub-unit</li> <li>Sub-unit</li> </ul> </li> <li>Unit- b <ul> <li>Sub-unit</li> <li>Sub-unit</li> </ul> </li> </ul> </li> </ul> </li> </ul> </html>

CSS counters() - 嵌套有序列表

在下面的示例中,`counters()` 函数用于根据名为 custom-counter 的计数器动态生成内容。

`counters()` 函数递增并检索指定计数器的值,允许自定义有序列表元素中列表标记和内容的格式。

Open Compiler
<html> <head> <style> ol { counter-reset: custom-counter; } li { counter-increment: custom-counter; } li::marker { content: counters(custom-counter, ".", lower-alpha) ") "; } li::before { content: counters(custom-counter, ". ") " -- " counters(custom-counter, "]. ", upper-roman); } </style> </head> <body> <ol> <li> <ol> <li></li> <li></li> <li></li> </ol> </li> <li> <ol> <li></li> <li></li> <li></li> </ol> </li> <li></li> <li> <ol> <li></li> <li> <ol> <li></li> <li></li> <li></li> </ol> </li> </ol> </li> </ol> </body> </html>
广告