CSS counter() 函数为您提供一个字符串,显示命名计数器的当前值。通常,它用于 伪元素 的 counter 属性。
可能的值
- <counter-name> - 这是计数器的唯一名称,必须与 counter-reset 和 counter-increment 中使用的大小写完全匹配。名称不能以两个连字符开头,并且不能是 none、unset、initial或inherit。
- <counter-style> - 这是可选的。计数器的样式(可以是 list-style-type 的值或@counter样式的值或 symbols() 函数。计数样式的名称可以很简单,例如数字、字母或符号等。
语法
counter(<countername>, <counterstyle>)
CSS counter() - 基本示例
下面是一个演示 counter() 函数的示例。
<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() 函数与两种不同计数器样式的用法。
<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>