说明:通过css计数器,我们可以只用一个简单的变量,来实现多个列表嵌套的排序输出。
原理:通过css计数器的自加功能实现编号的目的。
用到的属性:
content-使用 ::before 和 ::after 伪元素来插入自动生成的内容
counter-reset-设置或添加计数器
counter-increment-用于增加计数器的值,可设置多个
counter()-将计数器的值添加到内容
counters()-将多个计数器的值添加到内容
属性的具体用法,counter()和counters()的区别如下代码所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
body {
counter-reset: section;
/* 设置计数器 */
}
h2::before {
counter-increment: section;
/* 用于增加计数器section的值*/
content: "Section " counter(section) ": ";
/*输出的内容是 “section ” + section的值 +“: ” */
}
</style>
</head>
<body>
<h2>第一行</h2>
<h2>第二行</h2>
<h2>第三行</h2>
</body>
</html>
输出内容如下所示:
下面是使用counters()的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>通过列表演示计数器的具体使用</title>
<style>
ol {
counter-reset: section;
/* 设置计数器section*/
list-style-type: none;
}
/* 每次多嵌套一个列表,通过ol列表将section的计数器个数加一个 */
li::before {
counter-increment: section;
/* 用于增加计数器的值 */
content: counters(section,".") " ";
/* 使用counters()属性调用每个section输出
如果有一个section则输出 section的值
如果有两个section则输出 section的值+“.”+另一个section的值
以此类推。*/
}
</style>
</head>
<body>
<ol>
<li>第一</li>
<li>第一
<ol>
<li>第二</li>
<li>第二</li>
<li>第二
<ol>
<li>第三</li>
<li>第三</li>
<li>第三</li>
</ol>
</li>
</ol>
</li>
</ol>
</body>
</html>
运行结果如下所示
如有错误请指出