CSS Counter是CSS原生的计数器,可以进行自动计数。使用它有利于文档内容的排版,使文档有序化。
counter的使用中需要用到的参数有:
counter-reset:创建或者重置一个计数器;
counter-increment:增加技术值;
content:插入生成内容;
counter()或counters():增加一个元素计数器的值;
<!DOCTYPE html>
<html>
<head>
<style>
body {
counter-reset: section;
}
h1 {
counter-reset: subsection;
}
h1:before {
counter-increment: section;
content: "Section " counter(section) ". ";
}
h2:before {
counter-increment: subsection;
content: counter(section) "." counter(subsection) " ";
}
</style>
</head>
<body>
<p><b>Note:</b> IE8 supports these properties only if a !DOCTYPE is specified.</p>
<h1>HTML tutorials</h1>
<h2>HTML Tutorial</h2>
<h2>XHTML Tutorial</h2>
<h2>CSS Tutorial</h2>
<h1>Scripting tutorials</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>
<h1>XML tutorials</h1>
<h2>XML</h2>
<h2>XSL</h2>
</body>
</html>
渲染结果:
对上例进行简单分析:遇到body元素,重设一级计数器;遇到h1元素,重设二级计数器;为每个h1标签按照一级标签进行计数自增,并增加内容为”Section”的头,content为“Section 一级id”;为每个h2标签按照二级标签进行计数自增,并将一级标签技术值加在其前边,内容为“一级id.二级id”。