CSSカウンタで見出しに章番号を振る方法

未分類
挨拶
くろやぎ
くろやぎ

こんにちは!くろやぎ(kuroyagi_info)です。

本や教科書を読んでいると「第○○章 第××節」という表示をよく見かけます。ブログ記事の見出しをこのような形に装飾できます。この記事では、CSSカウンタで見出しに章番号を振る方法を紹介します。

  • 対象読者
    • 記事内のタイトルに章番号を振りたい

CSSカウンタとは何か

CSSカウンタとは、任意のHTML要素の数に従ってナンバリングする機能です。 contentプロパティのcounter()関数を使うことで、擬似クラス(:after:before)にナンバーを出力できます。

CSSカウンタの使い方

CSSカウンタを使うためには、counter-resetcounter-incrementという2つのプロパティを理解する必要があります。

  • counter-reset:カウンタをリセット
  • counter-increment:カウンタに1を足す

counter-resetに設定する値は任意です。 C言語で例えると、int i = 0;という文で、変数iを初期化する処理です

counter-incrementを設定した要素が呼び出されると、先ほどリセットしておいたカウンタに1が足されます。 C言語で例えると、i++;でカウントアップする処理です。

CSSカウントを用いて見出しに章番号を振る

それでは、ブログの記事内タイトルに章番号を振るコードを紹介します。 まず、完成予想図です。

次のコードをデザインCSSに追記します。

.entry-title {
    counter-reset: h2;
}

.entry-content h2 {
    counter-increment: h2;
    counter-reset: h3;
}

.entry-content h3 {
    counter-increment: h3;
    counter-reset: h4;
}

.entry-content h4 {
    counter-increment: h4;
    counter-reset: h5;
}

.entry-content h5 {
    counter-increment: h5;
    counter-reset: h6;
}

.entry-content h6 {
    counter-increment: h6;
}

.entry-content h2:before {
    content: counter(h2) ". ";
}

.entry-content h3:before {
    content: counter(h2) "." counter(h3) ". ";
}

.entry-content h4:before {
    content: counter(h2) "." counter(h3) "." counter(h4) ". ";
}

.entry-content h4:before {
    content: counter(h2) "." counter(h3) "." counter(h4) ". " counter(h5) ". ";
}

.entry-content h4:before {
    content: counter(h2) "." counter(h3) "." counter(h4) ". " counter(h5) ". " counter(h6) ". ";
}

見出しはh2からh6に対応しています。 contentプロパティの値を変更することで、章番号のデザインを変更できます。

おわりに

記事内のタイトルを「第○○章 第××節」のように変更したいときは、ぜひこの記事を参照しながら実装してみてください。

360
タイトルとURLをコピーしました