CSS 函数

CSS counter() 函数为您提供一个字符串,显示指定计数器的当前值。通常,它用在 pseudo-elementscontent 属性中.

可能的值

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

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

语法

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>第一项</li>
     <li>第二项</li>
     <li>第三项</li>
     <li>第四项</li>
     <li>第五项</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>这是第一项</li>
  <li>这是第二项</li>
  <li>这是第三项</li>
  <li>这是第四项</li>
  <li>这是第五项,也是最后一项</li>
</ul>
</body>
</html>