CSS-计数器 counter-reset、counter-increment、counter-reset

计数器

CSS的计数器通过在 content 上应用 counter() 或 counters()函数来显示计数的。其中计数器是由counter-reset和counter-increment 来进行操作的。

counter-increment

语法

  • counter-increment
  • 参数1:计算器名称 该标识符由不区分大小写的字母 a 到 z,数字 0 到 9,下划线(_)和/或短划线( - )的组合组成。第一个非破折号字符必须是一个字母(即,在它的开头没有数字,即使前面有破折号。)此外,在标识符的开头禁止使用两个破折号。在任何案例组合中都不能是 none,unset,initial 或 inherit。
  • 参数2:计数器的值。如果没有给出,默认为 1

普通版本

css 复制代码
    .one {
      /* 用于重置计数器的初始值,这里将计数器命名为 "oneCounter"  */
      counter-reset: oneCounter;

      /* 值 初始化是1, 不写的话,默认值是 0 */
      /* counter-reset: oneCounter 1; */
    }
    .one p::before {
      counter-increment: oneCounter 1;
      /* counter */
      content: counter(oneCounter) " 段 "
    }
html 复制代码
  <div class="one">
    <p>北国风光</p>
    <p>千里冰封</p>
    <p>万里雪飘</p>
    <p>望长城内外</p>
    <p>惟余莽莽</p>
    <p>大河上下</p>
    <p>顿失滔滔</p>
  </div>

如果 counter-increment: oneCounter 2; 这样写,就是,第一行是初始化的值 + 2,下面的行,依次 + 2

如果 counter-reset: oneCounter 10; counter-increment: oneCounter 2;

多个计数器呢?

属于同一个父级元素,才会累计,不是一个父元素不会冲突

html 复制代码
  <style>
    .one {
      /* 用于重置计数器的初始值,这里将计数器命名为 "oneCounter"  */
      counter-reset: oneCounter twoCounter 30;

      /* 值 初始化是1, 不写的话,默认值是 0 */
      /* counter-reset: oneCounter 1; */

    }

    .one p::before {
      counter-increment: oneCounter 2;
      /* counter */
      content: counter(oneCounter) " 段 "
    }

    .two p::before {
      counter-increment: twoCounter 10;
      /* counter */
      content: counter(twoCounter) " 段 "
    }
  </style>
</head>

<body>

  <div class="one">
    <p>北国风光</p>
    <p>千里冰封</p>
    <p>万里雪飘</p>
    <p>望长城内外</p>
    <p>惟余莽莽</p>
    <p>大河上下</p>
    <p>顿失滔滔</p>
  </div>
  <br>
  <div class="two">
    <p>北国风光</p>
    <p>千里冰封</p>
    <p>万里雪飘</p>
    <p>望长城内外</p>
    <p>惟余莽莽</p>
    <p>大河上下</p>
    <p>顿失滔滔</p>
  </div>
</body>

降序

css 复制代码
    .one {
      /* 用于重置计数器的初始值,这里将计数器命名为 "oneCounter"  */
      counter-reset: oneCounter-reversed -2 twoCounter 30;

      /* 值 初始化是1, 不写的话,默认值是 0 */
      /* counter-reset: oneCounter 1; */

    }

    .one p::before {
      counter-increment: oneCounter-reversed -2;
      /* counter */
      content: counter(oneCounter-reversed) " 段 "
    }
相关推荐
人工智能训练师1 天前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny071 天前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy1 天前
css的基本知识
前端·css
昔人'1 天前
css `lh`单位
前端·css
Nan_Shu_6141 天前
Web前端面试题(2)
前端
知识分享小能手1 天前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
2501_918126911 天前
用html5写一个flappybird游戏
css·游戏·html5
蚂蚁RichLab前端团队1 天前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光1 天前
css之一个元素可以同时应用多个动画效果
前端·css
huangql5201 天前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js