[CSS] Explaining the counters() function that supports hierarchical structures instead of just counter()
![[CSS] Explaining the counters() function that supports hierarchical structures instead of just counter()](img/ogp.png)
There is a function called "counter()" that allows for numbering in CSS.
For example, with this HTML:
<ul class="counter">
<li>リスト</li>
<li>リスト</li>
<li>リスト</li>
<li>リスト</li>
</ul>
If you write this CSS:
.counter {
counter-reset: number;
}
.counter li::before {
counter-increment: number;
content: counter(number);
}
It will be output like this:
- リスト
- リスト
- リスト
- リスト
On the other hand, there is also a function called "counters()".
Using this,
When you have a hierarchical structure like this, you can number by inheriting the parent's number.
- リスト
- リスト
- 子リスト
- 子リスト
- リスト
- 子リスト
- 子リスト
- 孫リスト
- 孫リスト
- リスト
This is done
with HTML like this:
<ul class="counters">
<li>リスト</li>
<li>リスト
<ul class="counters">
<li>子リスト</li>
<li>子リスト</li>
</ul>
</li>
<li>リスト
<ul class="counters">
<li>子リスト</li>
<li>子リスト
<ul class="counters">
<li>孫リスト</li>
<li>孫リスト</li>
</ul>
</li>
</ul>
</li>
<li>リスト</li>
</ul>
and CSS like this:
.counters {
counter-reset: lists;
}
.counters li::before {
counter-increment: lists;
content: counters(lists, "-");
}
content: "任意の文字" counters(カウンター名, "区切り文字") "任意の文字";
It is written as follows.
For example,
if you do this:
content: counters(lists, ".");
it will look like this:
- リスト
- 子リスト
- 子リスト
- 孫リスト
- 孫リスト
- リスト
if you do this:
content: "[" counters(lists, ".") "] : ";
it will look like this:
- リスト
- 子リスト
- 子リスト
- 孫リスト
- 孫リスト
- リスト
I hope this has been helpful.
Using CSS counters - CSS: Cascading Style Sheets | MDN




If this was helpful, we appreciate your support!
Any support received will be used for childcare.
Or support us by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
楽天市場
Yahoo!ショッピング
PR