就是采用css给一些html元素自动生成编号,好比相似1.3.2
这种,先看个效果:css
对,就是这种相似Word里面很常见的效果,代码以下:html
<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
在你须要开始计数的地方重置计数器:bash
ol { counter-reset: section; }
复制代码
而后经过counter-increment
指定计数器什么时候自增,好比这里是碰到li
就自增,因此咱们写在li
上面:ide
ol li { counter-increment: section; }
复制代码
最后,就是如何显示计数器了。显示计数器有2种方式,counter和counters,先讲counter。ui
counterspa
counter只是简单的从前至后计数,忽略嵌套,语法以下:ssr
counter(计数器名称[, 可选的显示风格]) // 默认风格为decimal
复制代码
其中第二个参数为可选,表示计数器显示的风格,例如,你能够使用upper-roman
以罗马数字显示,默认为decimal
,即数字形式,其可选值大部分和css的 list-style-style 的一致,除了以下几个不被支持(不一样浏览器支持的程度不同):code
咱们使用counter
把它显示到li
的:before
上面,并指定以大写罗马数字显示:cdn
ol li:before { content: counter(section, upper-roman) ". ";}
复制代码
效果以下:
counters
下面再来看看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) "、"; }
复制代码
效果:
#demo6 ol { counter-reset: section 5; }
#demo6 ol li { counter-increment: section; }
#demo6 ol li:before { content: counter(section) ". "; }
复制代码
#demo7 ol { counter-reset: section 5; }
#demo7 ol li { counter-increment: section 2; }
#demo7 ol li:before { content: counter(section) ". "; }
复制代码
#demo8 ol { counter-reset: section 6; }
#demo8 ol li { counter-increment: section -1; }
#demo8 ol li:before { content: counter(section) ". "; }
复制代码
#demo9 ol { counter-reset: section; }
#demo9 ol li { counter-increment: section; }
#demo9 ol li:before { content: "==" counter(section, lower-alpha) counters(section, '-') "** "; }
复制代码
查看完整demo请用力猛戳:demo.liuxianan.com/2016/03/08-…