Calleigh’s blog

幸せは毎日の食卓から

counter-incrementプロパティ|CSS

CSSのcounter-increment要素を使って見出し(h1、h2、h3...)に自動で連番を付すときの注意点。

:before疑似要素を利用して自動でやってもらおうと

h2:before{
    counter-reset: subsection;
    counter-increment: section;
    content: "第"counter(section)"節 ";
}
h3:before{
    counter-increment: subsection;
    .
    .
    .

と書いたら、h2の見出しすべてが第1節 見出しになってしまった。
使用ブラウザはGoogleChrome。以前はできたのに何故だと調べてみると、

  • 古いブラウザだと上記のプロパティに対応していないものもある
  • 古いブラウザだと:before疑似要素、:after疑似要素に対応していないものもある
  • ブラウザによって(?)はcounter-resetプロパティを設定すれば表示される

くらいの情報しか出てこなかった。
GoogleChromeではいずれのプロパティも、疑似要素も対応しているので、counter-resetを全てのcounterに対して設定してみたがカウントアップをしない。

結局、:before疑似要素が必要なcontentプロパティと、その他のプロパティで分けて書いたら解決した。

h2{
    counter-reset: subsection;
    counter-increment: section;
}
h2:before{
    content: "第"counter(section)"節 ";
}
h3
    .
    .
    .

試したのが結構前で忘れていたため、調べるのに時間を使ってしまったのでメモ。


【参考サイト】
counter-increment - CSS: Cascading Style Sheets | MDN web docs
CSS counter-increment property | W3Schools
counter-increment スタイルシートリファレンス|HTMLクイックリファレンス