LoginSignup
15
19

More than 5 years have passed since last update.

CSSで見出し要素(h1, h2...)の前に自動で採番する方法

Last updated at Posted at 2017-05-07

例えば、h1タグは"1. 最初の章", "2. 次の章"というように章番号をふることはよくある。
そのときに、手動で採番するのは保守性が悪いし、美しくない。
そんなときはCSSのcounter機能を用いると簡単に自動採番できる。

サンプルコード
body {
    counter-reset: chapter;
}
h1 {
  counter-reset: sub-chapter;
}
h2 {
  counter-reset: section;
}

h1::before {
  counter-increment: chapter;
  content: counter(chapter) ". ";
}
h2::before {
  counter-increment: sub-chapter;
  content: counter(chapter) "-" counter(sub-chapter) ". ";
}
h3::before {
  counter-increment: section;
  content: "(" counter(section) ") ";
}

MDN

仕様は次で確認。

Using CSS counters - CSS | MDN

(おまけ)Atomのマークダウンプレビューで設定する方法

基本は同じ。
Atomのstyleはメニューの[Stylesheet]からstyle.lessを開いて編集する。
ポイントは、bodyはmarkdown-previewの外なので、上記設定をすべて.markdown-previewの中にいれるとうまくいかない。

style.less
// for markdown-preview
body {
    counter-reset: chapter;
}
h1 {
  counter-reset: sub-chapter;
}
h2 {
  counter-reset: section;
}
.markdown-preview {
  h1::before {
    counter-increment: chapter;
    content: counter(chapter) ". ";
  }
  h2::before {
    counter-increment: sub-chapter;
    content: counter(chapter) "-" counter(sub-chapter) ". ";
  }
  h3::before {
    counter-increment: section;
    content: "(" counter(section) ") ";
  }
}
15
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
19