前言
在CSS3之前,只有ul和ol等列表元素中存在计数器,其他元素很难通过CSS实现计数功能。而CSS3之后,通过新增的counter属性,可以实现任意元素的计数。
使用
以本博客的代码行计数功能为例,代码标签构成方式如下:

页面展示效果如下:

可以看出,<pre>标签嵌套<span>标签,<pre>标签为整段代码,<span>标签为单行代码,因此计数代码行数也就是对<span>标签的计数。
在后台CSS中增加以下CSS代码:
pre { ... position: relative; counter-reset: step 0; } pre span:before { position: absolute; content: counter(step); counter-increment: step 1; color: black; border-right: solid 2px #eb7350; }
其中counter、counter-reset、counter-increment是最主要的属性,counter用于设置计数器的名称,counter-reset写在父元素中用于限定计数范围并将计数器重置为初始值,counter-increment则写到子元素中,每次出现子元素,对计数器进行累加。
注意,通过将display属性设置为none或者hidden而隐藏的子元素不参与计数,而通过visibility:hidden等方式隐藏的子元素仍然参与计数。
得到以下效果:

像代码中一样,counter经常和伪元素搭配使用,避免污染被计数的元素,例如复制代码时不会复制到行数。

后话
为了兼容这个代码行数计算功能,我把之前发的上百篇博客挨个整理了一下,提前近一个月完成了早期博客的基本重构(尤其是被垃圾评论们骚扰最多的命令行工具nircmd,当时都写的什么玩意儿,直接重新写了),也算是拔了一月份立下的一个flag,后面的详细优化就可以慢慢来了。
女人固然是脆弱的,
母亲却是坚强的。
——维克多·雨果


评论
803038 509571I truly treasure your piece of work, Great post. CHECK ME OUT BY CLICKING MY NAME!!! 363898
698133 612604Someone essentially lend a hand to make critically articles Id state. That may be the 1st time I frequented your site page and so far? I amazed with the research you made to create this actual post extraordinary. Amazing activity! 356830
13450 545329This style is steller! You naturally know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (nicely, almostHaHa!) Great job. I truly enjoyed what you had to say, and much more than that, how you presented it. Too cool! 777779
677402 149882Spot ill carry on with this write-up, I truly think this internet site requirements an excellent deal more consideration. Ill oftimes be once more to see far much more, a lot of thanks that information. 374355
218891 657206For anyone one of the lucky peoples, referring purchase certain products, and in addition you charm all with the envy of all of the the several any other individuals about you that tend to have effort as such make a difference. motor movers 688666
83153 391801I love reading by way of and I believe this internet site got some genuinely utilitarian stuff on it! . 197079
400229 33555Some truly quality weblog posts on this site, saved to fav. 21239