CSSで自動連番を表示する

CSSで自動連番を表示する方法のご紹介です。

タイトルにセクション番号やチャプター番号をつけたい場合に便利です。

 

 

 HTMLは以下のようになります。(要素はなんでもかまいません)

<body>

<section>

<h2>あいうえお</h2>

 <h2>かきくけこ</h2>

<h2>さしすせそ</h2>

</section>

<section>

<h2>たちつてと</h2>

<h2>なにぬねの</h2>

</section>

<section>

<h2>はひふへほ</h2>

<h2>まみむめも</h2>

<h2>やゆよ</h2>

</section>

</body>

 

ページ全体で通しの連番にするCSS

body{ counter-reset:title;}

h2{counter-increment:title;}

h2:before {
  content: counter(title);

}

 

section内で通しの連番にするCSS

section{ counter-reset:title;}

h2{counter-increment:title;}

h2:before {
  content: counter(title);

}

 

titleというのは任意につけられるカウンターの名前です。好きな名前にできます。