CSS: counter-increment 見出し等に連番を振る
CSSで見出し要素等に連番を振る場合は、counter-incrementプロパティや、 counter-resetプロパティを使用します。
2つを使うことで h1 要素や h2 要素等の要素にも自動的に番号を振ることができます。
counter-increment プロパティの使用例
h1:before {
content: count(chapter) "章 ";
counter-increment: chapter;
}
上記で使用されている「chapter」はカウンタ名といい、変数の役割を果たしています。 番号を使用する場合は、content プロパティの counter() 関数を使って使用します。
連番を振るサンプルコード
次のコードは h4 要素を大見出し、 h5 要素を小見出しとして先頭に連番を振るようにしています。 大見出しは「n章 」、小見出しは「n-n 」と先頭に加えています。 カウンタ名は chapter、section です。
<h4>大見出し</h4>
<h5>小見出し</h5>
<h5>小見出し</h5>
<h4>大見出し</h4>
<h5>小見出し</h5>
<h5>小見出し</h5>
<h5>小見出し</h5>
<style>
body {
counter-reset: chapter;
}
h4:before {
content: counter(chapter) "章. ";
counter-increment: chapter
}
h4 {
counter-reset: section;
}
h5:before {
content: counter(chapter) "-" counter(section) " ";
counter-increment: section;
}
</style>
表示結果: