首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

计数器 | <counter>

CSS counters 让您根据在文档中的位置调整内容的外观。例如,您可以使用计数器自动为网页中的标题编号。计数器本质上是由CSS维护的变量,其值可以通过CSS规则递增来追踪它们被使用的次数。

使用计数器

操作计数器的值

要使用CSS计数器,必须首先将其初始化为具有该counter-reset属性的值(默认情况是0)。也可以使用相同的属性将其值更改为任何特定的数字。一旦初始化,一个计数器的值可以通过counter-increment增加或减少。计数器的名称不得为“none”,“inherit”或“initial”。否则声明被忽略。

显示计数器

counter()函数有两种形式:‘counter(name)' 或 'counter(name, style)‘。生成的文本是给定伪元素范围内给定名称的最内层计数器的值。它被格式化为指定的样式(默认是decimal)。

counters()函数还有两种形式: 'counters(name, string)' 或'counters(name, string, style)'。生成的文本是给定伪元素的所有具有给定名称的计数器的值,从最外层到最内层,由指定的字符串分隔。计数器以指定的样式呈现(默认是decimal)。

基本实例

本示例将“计数器的值:”部分添加到每个标题的开头。

CSS

代码语言:javascript
复制
body {
  counter-reset: section;                     /* Set a counter named 'section', and it`s initial value is 0. */
}

h3::before {
  counter-increment: section;                 /* Increment the value of section counter by 1 */
  content: counter(section);                  /* Display the value of section counter */
}

HTML

代码语言:javascript
复制
<h3>Introduction</h3>
<h3>Body</h3>
<h3>Conclusion</h3>

结果

嵌套计数器

CSS计数器对于创建概要列表可能特别有用,因为计数器的新实例是在子元素中自动创建的。使用counters()https://developer.mozilla.org/en-US/docs/Web/CSS/counters)函数,可以在不同级别的嵌套计数器之间插入分隔文本。

嵌套计数器示例

CSS

代码语言:javascript
复制
ol {
  counter-reset: section;                /* Creates a new instance of the
                                            section counter with each ol
                                            element */
  list-style-type: none;
}

li::before {
  counter-increment: section;            /* Increments only this instance
                                            of the section counter */
  content: counters(section, ".") " ";   /* Combines the values of all instances
                                            of the section counter, separated
                                            by a period */
}

HTML

代码语言:javascript
复制
<ol>
  <li>item</li>          <!-- 1     -->
  <li>item               <!-- 2     -->
    <ol>
      <li>item</li>      <!-- 2.1   -->
      <li>item</li>      <!-- 2.2   -->
      <li>item           <!-- 2.3   -->
        <ol>
          <li>item</li>  <!-- 2.3.1 -->
          <li>item</li>  <!-- 2.3.2 -->
        </ol>
        <ol>
          <li>item</li>  <!-- 2.3.1 -->
          <li>item</li>  <!-- 2.3.2 -->
          <li>item</li>  <!-- 2.3.3 -->
        </ol>
      </li>
      <li>item</li>      <!-- 2.4   -->
    </ol>
  </li>
  <li>item</li>          <!-- 3     -->
  <li>item</li>          <!-- 4     -->
</ol>
<ol>
  <li>item</li>          <!-- 1     -->
  <li>item</li>          <!-- 2     -->
</ol>

结果

规格

Specification

Status

Comment

CSS Lists and Counters Module Level 3The definition of 'CSS Counters' in that specification.

Working Draft

No change

CSS Level 2 (Revision 1)The definition of 'CSS Counters' in that specification.

Recommendation

Initial definition

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com