css实现标题自动编号
有些页面中会有不同的标题,就像word文档一样有大标题或者子标题,在文档中我们可以在word中可以自动编号,但是在代码中一般来说就会手动编写,但是要是在中间添加或者删除某一项的话,编号就会乱掉,那我们只能重新编写,很麻烦,那今天就了解一下css的自动编号吧。
css的content属性可以实现自动编号,下面来看一下效果。
通过下面的图片可以看出是没有编号的,那这就是有css控制的自动编号。
首先我们先来了解一下css的counter属性,其有三个属性分别是counter-reset属性、counter-increment属性、counter()方法。
1.counter-reset属性表示设置某个计数器的值。
使用示例
counter-reset: cnt_h2; /* 设置cnt_h2,默认从0开始 */
counter-reset: cnt_h3 1; /* 设置cnt_h3,从1开始 */
counter-reset: cnt_h4 1 cnt_h5 2; /* 设置cnt_h4从1开始,cnt_h5从2开始 */
2.counter-increment属性表示给某计数器的值加1。例如:counter-increment: cnt_h3
(默认增加1)或counter-increment: cnt_h4 2
(指定增加2)。
3.counter()方法获取计数器的值,默认的编号类型是数字。当然,除数字外,也可以使用字母、罗马数字等,只需在 counter 中指定编号种类即可,编号种类可以是 list-style-type 属性能支持的任何值。如:content: counter(counter_h1, lower-roman);
list-style-type支持的值有
例子的整体代码,有不足的地方欢迎指证交流。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css自动编号</title>
</head>
<style>
h1,h2,h3{
padding: 0;
margin: 0;
font-weight: normal;
}
h1 {
counter-increment: counter_h1;
}
h1::before {
content: counter(counter_h1)".";
}
h2 {
counter-increment: counter_h2;
counter-reset: counter_h3;
padding-left: 20px;
}
h2::before{
content: counter(counter_h1)"."counter(counter_h2)"."
}
h3 {
counter-increment: counter_h3;
padding-left: 40px;
}
h3::before {
content: counter(counter_h1)"."counter(counter_h2)"."counter(counter_h3)".";
}
</style>
<body>
<h1>一级标题</h1>
<h2>二级标题</h2>
<h3>三级标题</h3>
<h3>三级标题</h3>
<h3>三级标题</h3>
<h3>三级标题</h3>
<h2>二级标题</h2>
<h3>三级标题</h3>
<h3>三级标题</h3>
<h3>三级标题</h3>
<h3>三级标题</h3>
</body>
</html>