Front-End & Daily

[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()

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

Comments

After reviewing the content, we will publish it, omitting personal information.

Enter your name and email address

Please enter if you would like a reply by email.

Personal information provided will not be disclosed. It will only be used for replies.

It will be sent directly. Please confirm and click "Send".

If this was helpful, we appreciate your support!
Any support received will be used for childcare.

Send support via OFUSE


Or support us by buying something from the buttons below
(You don't have to buy the linked product.)

Amazon

楽天市場

Yahoo!ショッピング

PR

As an Amazon Associate, "Ken" earns income from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark