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>)

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>
廣告
© . All rights reserved.