CSS – Counters

介绍

counter 有点像 JS 的 for loop index. 最常用到的地方就是做 ol > li.

 

参考:

W3Schools – CSS Counters

 

默认 ol > li

<ol>
  <li>
    Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum
    dolor sit amet.
  </li>
  <li>Lorem ipsum dolor sit amet.</li>
</ol>

效果

 

 1, 2 号码是默认的, 如果我想在 number 前面加上 Step 字眼:

 

 可以通过 CSS

ol {
  padding-left: 7ch;
  li {
    &::marker {
      content: "Step " counter(list-item) ": ";
    }
  }
}

这里就用到了 counter

 

reset, increment, counter()

它的 3 步骤就是 declare/reset, increase, use it. 

复制代码
ol {
  padding-left: 7ch;
  counter-reset: my-counter; // index = 0
  li {
    counter-increment: my-counter; // index++
    &::marker {
      content: "Step " counter(my-counter) ": "; // get index
    }
  }
}
复制代码

每当遇到 ol, 它就会 reset 1 个新的 variable.

li 就 increase

::marker 时就调用输出.

输出不同格式

输出的时候还可以选择各做格式, 比如 alphabet, decimal 等等

&::marker {
  content: "Step " counter(my-counter, lower-alpha) ": "; // get index
}

在第 2 参数写上 lower-alpha, 就会输出 a, b, c 了. (注: zero 输出 alpha 还是 zero 哦)

可以参考 list-style-type, 全都可以用在 counter 参数格式

层中层

CSS Style

复制代码
ol {
  counter-reset: section;
  list-style-type: none;
}

li::before {
  counter-increment: section;
  content: counters(section,".") " ";
}
复制代码

关键在 "."

 

posted @   兴杰  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示