counter-reset、counter-increment、counter()的使用
在实现元素编号中,可以用 ol li 制作有序列表,但是处理不了复杂点的排序,这时候就可以用到counter-reset、counter-increment、counter()这三个属性了
1、先实现简单的排序
ul{
margin: 0;
padding: 0;
list-style: none;
/* main为自定义名称,与counter-increment和counter使用的名称对应 */
counter-reset: main;
}
li::before{
list-style: none;
counter-increment: main;
content: counter(main);
}
<h4>元素序号</h4>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
2、实现复杂点的排序
只要设置了counter-reset的元素就相当于一个搁板,只要在搁板底下,子部分(这里的h2)就会重新计数,不管子部分嵌套多少层都能够计算上去
body{
counter-reset: title;
}
h1{
margin: 0;
padding: 0;
counter-reset: subtitle;
list-style: none;
}
h2{
padding-left: 40px;
}
h1::before{
content: counter(title) '、';
counter-increment: title;
}
h2::before{
list-style: none;
counter-increment: subtitle;
content: counter(title) '-' counter(subtitle) ' ';
}
<body>
<h1>主标题1</h1>
<h2>副标题1</h2>
<h2>副标题2</h2>
<div>
<div>
<span>
<h2>副标题</h2>
</span>
</div>
</div>
<h1>主标题2</h1>
<h2>副标题</h2>
</body>