体验更佳排版请戳原文链接:http://blog.liuxianan.com/css-counters.html
就是采用css给一些html元素自动生成编号,比如类似1.3.2这种,先看个效果:
对,就是这种类似Word里面很常见的效果,代码如下:
<style type="text/css"> #demo1 ol { counter-reset: section; list-style-type: none; } #demo1 ol li { counter-increment: section; } #demo1 ol li:before { content: counters(section, ".") ". "; } </style> <div id="demo1"> <ol> <li>进风口的爽肤水 <ol> <li>非进口商的</li> <li>非进口商的</li> <li>非进口商的</li> </ol> </li> <li>进风口的爽肤水 <ol> <li>非进口商的</li> <li> 非进口商的 <ol> <li>将咖啡色的开发商</li> <li>将咖啡色的开发商</li> <li>将咖啡色的开发商</li> <li>将咖啡色的开发商</li> </ol> </li> <li>非进口商的</li> </ol> </li> <li>进风口的爽肤水</li> </ol> </div>IE8+,Chrome和Firefox支持良好。属于CSS2范畴。
首先,给我们的计数器取一个名字,这个名字可以随便取,比如这里叫section,然后使用counter-reset在你需要开始计数的地方重置计数器:
ol { counter-reset: section; }然后通过counter-increment指定计数器何时自增,比如这里是碰到li就自增,所以我们写在li上面:
ol li { counter-increment: section; }最后,就是如何显示计数器了。显示计数器有2种方式,counter和counters,先讲counter。
counter只是简单的从前至后计数,忽略嵌套,语法如下:
counter(计数器名称[, 可选的显示风格]) // 默认风格为decimal其中第二个参数为可选,表示计数器显示的风格,例如,你可以使用upper-roman以罗马数字显示,默认为decimal,即数字形式,其可选值大部分和css的 list-style-style 的一致,除了如下几个不被支持(不同浏览器支持的程度不一样):
circlesquarelower-alphaupper-mongolian我们使用counter把它显示到li的:before上面,并指定以大写罗马数字显示:
ol li:before { content: counter(section, upper-roman) ". ";}效果如下:
下面再来看看counters,counters和counter的最大区别是它会嵌套,什么是嵌套,我的表达能力有限,但我想大部分看到这里应该都明白了,就是类似1.3.8这种,
语法如下:
counters(计数器名称, 嵌套时拼接字符串[, 可选的显示风格])比如我们使用点号.分割,
ol li:before { content: counters(section, "."); }另外,你可以将counters或者counter与任意字符串用空格拼接:
ol li:before { content: "我是字符串1" counters(section, ".") "我是字符串2" "我是字符串3"; }甚至counter和counters混用:
ol li:before { content: counter(section) ". " counters(section, ".", lower-alpha) ". "; }效果如下:
部分浏览器可能不支持:
#demo5 ol { counter-reset: section; } #demo5 ol li { counter-increment: section; } #demo5 ol li:before { content: counter(section, cjk-ideographic) "、"; }效果:
查看完整demo请用力猛戳:http://mygit.me/html/2016/0308-css-counter.html
https://dev.opera.com/articles/automatic-numbering-with-css-counters/
转载于:https://www.cnblogs.com/liuxianan/p/css-counters.html
相关资源:CSS计数器(序列数字字符自动递增)详解