CSS 计数器本质上是 CSS 维护的变量,这些变量能够根据 CSS 规则增长以跟踪使用次数。css
那么关于 CSS 计数器的使用,就须要读者智者见智了。有网友利用计数器制做文档的列表序号排序,也有网友利用计数器 + 伪类元素制做更华丽的效果。html
1.命名变量并定义计数器的值,默认为 0。wordpress
counter-reset: varname;
递增计数器的值,默认增量为 1。code
counter-increment: varname;
counter() / counters() 方法显示计数。htm
counter(varname);
CSS 计数器只跟
content
属性使用才有效。
counter-reset
默认值counter-reset: varname number;
容许设置为负值,也容许设置为小数( 仅 Chrome 支持)。同时,也支持多个变量同时定义:
counter-reset: varname1 number varname2 number varname3 number;
HTML排序
<div class="box"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> <input type="checkbox"> </div>
CSSrem
.box { counter-reset: num; } input:checked { counter-increment: num; } input:checked:before { content: counter(num); }
HTML文档
<div class="box"> <h1>文章目录标题1</h1> <h1>文章目录标题2</h1> <h1>文章目录标题3</h1> <h1>文章目录标题4</h1> <h1>文章目录标题5</h1> </div>
CSSget
.box { counter-reset: num; } h1 { counter-increment: num; } h1:before { content: counter(num); }
HTMLinput
<div class="box"> <h1>文章目录标题</h1> <h2>文章目录副标题</h2> <h1>文章目录标题</h1> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h1>文章目录标题</h1> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h1>文章目录标题</h1> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h1>文章目录标题</h1> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> <h2>文章目录副标题</h2> </div>
CSS
.box { counter-reset: num; } h1 { counter-reset: subnum; counter-increment: num; } h1:before { content: counter(num); } h2 { counter-increment: subnum; } h2:before { content: counter(num)"."counter(subnum); }
在上面的案例及分享中,其实讲到的东西很是少。想要更深了解 CSS 计数器的读者,能够阅读张鑫旭先生这篇《CSS counter计数器(content目录序号自动递增)详解》。