※当サイトはアフィリエイト広告を使用しています。
こんにちは。すずきです。
CSS の counter を「常に 2 桁(01, 02, …, 10, 11…)」で出すやり方を、最短コードから応用までまとめ直しました。
もう「010」問題とはサヨナラです。
目次
結論:CSSで「2桁カウンター」を出す最短コード
<h2>見出し</h2>
<h2>見出し</h2>
<h2>見出し</h2>
/* まずカウンターを用意 */
body { counter-reset: h2; }
/* 番号を 2 桁で前置 */
h2::before {
counter-increment: h2;
content: counter(h2, decimal-leading-zero) ". ";
}
これで 01. 見出し / 02. 見出し / … / 10. 見出し
と自動で出ます。
CSSカウンターの基本
body { counter-reset: item; }
h2::before {
counter-increment: item;
content: counter(item); /* スタイル省略 = 素の数字 */
}
Using CSS counters - CSS | MDN
CSS counters let you adjust the appearance of content based on its location in a document.
For example, you can use counters to automaticall...
counter() - CSS | MDN
The counter() CSS function returns a string representing the current value of the named counter, if there is one.
2 桁で出すやり方 3 パターン
いちばん簡単:counter(name, decimal-leading-zero)
h2::before {
counter-increment: h2;
content: counter(h2, decimal-leading-zero) " ";
}
1〜9 にだけ 0 が付きます。10 以上はそのまま。99 まできれいに出ます。
list-style-type - CSS | MDN
The list-style-type CSS property sets the marker (such as a disc, character, or custom counter style) of a list item element.
カスタム派に:@counter-style
+ pad: 0 2;
もっと明示的に「2 桁パディング」を指定したい場合。
@counter-style two-digit {
system: numeric;
symbols: 0 1 2 3 4 5 6 7 8 9;
pad: 0 2; /* 2 桁になるまで 0 で埋める */
}
body { counter-reset: sec; }
h2::before {
counter-increment: sec;
content: counter(sec, two-digit) ". ";
}
pad: 0 2;
は 最低 2 桁 を保証。100 以降は 100
のように自然に 3 桁表示になります。
@counter-style - CSS | MDN
The @counter-style CSS at-rule lets you extend predefined list styles and define your own counter styles that are not part of the predefined...
セクションごとにリセットしたい
カード一覧など「コンテナごとに 01, 02…」を振る例。
<section class="list">
<article class="card">A</article>
<article class="card">B</article>
</section>
<section class="list">
<article class="card">C</article>
<article class="card">D</article>
</section>
.list { counter-reset: card; }
.card::before {
counter-increment: card;
content: counter(card, decimal-leading-zero) " ";
font-variant-numeric: tabular-nums; /* 桁揃え */
}
まとめ
この 3 点を押さえれば、デザインでよくある「01, 02…」は全部 CSS だけでさばけます。どう使うかはプロジェクト次第でどうぞ。
Using CSS counters - CSS | MDN
CSS counters let you adjust the appearance of content based on its location in a document.
For example, you can use counters to automaticall...
counter() - CSS | MDN
The counter() CSS function returns a string representing the current value of the named counter, if there is one.
@counter-style - CSS | MDN
The @counter-style CSS at-rule lets you extend predefined list styles and define your own counter styles that are not part of the predefined...