CSS カウンタは、「変数」のようなものです。変数の値は、(使用された回数を追跡する)CSS ルールによって増分することができます。
CSS カウンタを取扱うには、次のプロパティを使用します:
counter-reset
- カウンタを作成またはリセットするcounter-increment
- カウンタの値を増分するcontent
- 生成されたコンテンツを挿入するcounter()
または counters()
関数 - カウンタの値を要素に追加するCSS カウンタを使用するには、最初に counter-reset
で作成しなければなりません。
次の例は、(body セレクタで)ページ用のカウンタを作成し、次に、各 <h2> 要素のカウンタ値を増分し、 各 <h2> 要素の先頭に "Section <value of the counter>:" を追加します:
body {
counter-reset: section;
}
h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}
Try it Yourself ❯
次の例は、ページ用のカウンタ(section) 1 つと、各 <h1> 要素用のカウンタ(subsection)を 1 つ作成します。 "section" カウンタは、"Section <section カウンタの値>." を持つ各 <h1> 要素をカウントし、 "subsection" カウンタは、"<section カウンタの値>.<subsection カウンタの値>" を持つ各 <h2> 要素をカウントします:
body {
counter-reset: section;
}
h1 {
counter-reset: subsection;
}
h1::before {
counter-increment:
section;
content: "Section " counter(section) ". ";
}
h2::before {
counter-increment: subsection;
content:
counter(section) "." counter(subsection) " ";
}
Try it Yourself ❯
カウンタの新しいインスタンスが、自動的に子要素に作成されるため、アウトライン付きのリストを作るためにカウンタは役立ちます。
ここでは、ネストしたカウンタの異なったレベルの間に文字列を挿入するために counters()
関数を使用します:
ol {
counter-reset: section;
list-style-type: none;
}
li::before {
counter-increment: section;
content: counters(section,".") " ";
}
Try it Yourself ❯
プロパティ | 説明 |
---|---|
content | 生成されたコンテンツを挿入するために、::before および ::after 擬似要素と一緒に使用する |
counter-increment | 1 つ以上のカウンタの値を増分する |
counter-reset | 1 つ以上のカウンタを作成またはリセットする |