1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CSSだけで数値をカウントする

Posted at

サンプルはこちら。

See the Pen counter-increment test by Kazuyoshi Goto (@KazuyoshiGoto) on CodePen.

HTMLにもCSSにも数値は書いておらず、連番リスト(ol)も使っていません。

変数をカウントする

h2 {
  counter-increment: x;
  counter-reset: y;
}
h3 {
  counter-increment: y;
}

h2,h3 の見出しに counter-increment というプロパティを使っています。

このプロパティはCSS内で変数を定義すると同時に、その変数を+1します。
上記の場合は h2 ごとに x が、h3ごとに y が1つ増える宣言をしています。

また h2 には counter-reset: y も宣言しています。
これは指定した変数を0に戻すプロパティです。

h3 ごとに増える y をリセットすることで、大見出し(h2)ごとに小見出し(h3)の番号を1から振り直す形になります。

ちなみに counter-increment: x y; という形で複数の変数を同時にカウントすることもできます。

変数を表示する

h2:before {
  content: "Part" counter(x) " : ";
}
h3:before {
  content: counter(x) "-" counter(y) " : ";
}

変数の表示ですが、現在 counter-increment で作った変数は疑似要素 :before:after の、 content でしか表示できません。

疑似要素に content: counter(x) で変数を表示することができますが、サンプルのように前後に文字を入れたり、複数の変数も表示できます。

「X章Y条」のように長い条項が続く文章も番号を意識せず作れますし、ほかにも連番が必要な時にプログラムに頼らず表示することができます。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?