背景
HTMLのリスト要素(<ol>
や<ul>
)は、通常、ブラウザにより自動でスタイルが適用される。例えば、順序付きリストでは「1.」「2.」といった数字が自動で付与される。しかし、開発現場では、数字の後にコロン(1:
)を付けたり、数字全体を括弧で囲む((1)
など)など柔軟なスタイルが求められるケースも多くある。
CSSの@counter-style
を利用して独自のカウンタスタイルを定義すれば、こうしたニーズに対応できる。
HTMLのリスト要素(<ol>
や<ul>
)は、通常、ブラウザにより自動でスタイルが適用される。例えば、順序付きリストでは「1.」「2.」といった数字が自動で付与される。しかし、開発現場では、数字の後にコロン(1:
)を付けたり、数字全体を括弧で囲む((1)
など)など柔軟なスタイルが求められるケースも多くある。
CSSの@counter-style
を利用して独自のカウンタスタイルを定義すれば、こうしたニーズに対応できる。
ユースケースを記載する。
CSSの@counter-style
ルールで、以下のような構文でリストのカウンタの接頭辞や接尾辞を柔軟にカスタマイズできる。
system: extends decimal;
decimal
)を拡張する。prefix:
suffix:
この仕組みを活用することで、リストの数字に括弧を付けたり、コロンを追加することが可能となる。
(1)
)@counter-style bracketed {
system: extends decimal;
prefix: '(';
suffix: ')';
}
ol.bracketed {
list-style-type: bracketed;
}
<ol class="bracketed">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
(1) First item
(2) Second item
(3) Third item
1:
)@counter-style coloned {
system: extends decimal;
suffix: ': ';
}
ol.coloned {
list-style-type: coloned;
}
<ol class="coloned">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
1: First item
2: Second item
3: Third item
- 1:
)@counter-style my-counter-style {
system: extends decimal;
prefix: '- ';
suffix: ': ';
}
ol.my-counter-style {
list-style-type: my-counter-style;
}
<ol class="my-counter-style">
<li>Alpha</li>
<li>Beta</li>
<li>Gamma</li>
</ol>
@counter-style
の主要なシンタックスは以下の通り。
カウンタの整数値を文字列表現するために使用するアルゴリズムを指定する。
@counter-style fisheye {
system: cyclic;
symbols: '◉';
suffix: ' ';
}
ul {
list-style: fisheye;
}
system
がcyclic
、numeric
、alphabetic
、fixed
のときに使用され、カウンタに表示される記号のリストを定義する。
@counter-style arrows {
system: cyclic;
symbols: → ↓ ← ↑;
suffix: ' ';
}
ol {
list-style: arrows;
}
system: additive
のときに使用され、数値と対応する記号のペアを定義する(大きい値から順に書く必要あり)。
@counter-style additive-example {
system: additive;
additive-symbols:
100 'C',
10 'X',
1 'I';
suffix: ' ';
}
ol {
list-style: additive-example;
}
カウンタの適用範囲(整数の最小値と最大値)を指定する。
@counter-style limited {
system: numeric;
symbols: 'A' 'B' 'C';
range: 1 3;
suffix: '. ';
}
ol {
list-style: limited;
}
各カウンタの先頭に付与される文字列。
@counter-style star {
system: numeric;
symbols: ★;
prefix: '(';
suffix: ')';
}
ol {
list-style: star;
}
各カウンタの末尾に付与される文字列。
@counter-style arrow {
system: numeric;
symbols: '>';
suffix: '→ ';
}
ol {
list-style: arrow;
}
負の数を表すための前置・後置記号を指定する。
@counter-style neg {
system: numeric;
symbols: '*';
negative: '(' ')';
suffix: ' ';
}
ol {
list-style: neg;
}
指定した桁数になるように、特定の文字で左側を埋める。
@counter-style padded {
system: numeric;
symbols: '0' '1' '2' '3' '4' '5' '6' '7' '8' '9';
pad: 3 '0';
suffix: ' ';
}
ol {
list-style: padded;
}
使用できない場合に代替として使用されるカウンタ名を指定する。
@counter-style custom {
system: cyclic;
symbols: '✪';
fallback: disc;
suffix: ' ';
}
ol {
list-style: custom;
}
@counter-style
を使うことで、CSSのみでリストカウンタの見た目を簡潔にカスタマイズできるようになる。特に、括弧やコロンといった装飾は、UIの文脈に応じてリストの可読性や印象を向上させる効果がある。各種シンタックスの組み合わせ次第で、ほかにもさまざまなパターンが表現可能である。