How work counter() and counters() in css?

How work counter() and counters() in css?

Published on Updated on

The CSS `counter()` and `counters()` functions are used to create and manipulate counters, which are used to number or label content on a web page. The `counter()` function is used to insert the value of a counter into a generated content element, while the counters() function is used to insert the values of multiple counters into a single generated content element.

Here's an example of how to use the `counter()` function to number a list:

ol {
  counter-reset: item;
}

li {
  counter-increment: item;
}

li:before {
  content: counter(item) ". ";
}

In this example, we're using the `counter-reset` property to initialize a counter named "item" on the `ol` element. We're also using the `counter-increment` property to increment the "item" counter on each `li` element. Finally, we're using the `content` property with the `counter()` function to insert the value of the "item" counter before each li element, followed by a period and a space.

The `counters()` function works similarly, but allows you to insert the values of multiple counters into a single generated content element. Here's an example of how to use `counters()` to create a nested list with multiple levels of numbering:

ol {
  counter-reset: item;
}

li {
  counter-increment: item;
}

li:before {
  content: counter(item) ". ";
}

ol ol {
  counter-reset: subitem;
}

ol ol li {
  counter-increment: subitem;
}

ol ol li:before {
  content: counters(item, ".") "." counter(subitem) " ";
}

In this example, we're using the `counter-reset` property to initialize two counters: "item" on the outer `ol` element and "subitem" on the inner `ol` element. We're also using the `counter-increment` property to increment each counter on the corresponding `li` elements.

Finally, we're using the `content` property with the `counters()` and `counter()` functions to insert the values of both counters before each li element in the nested list. The `counters()` function inserts the values of the "item" counter and all its ancestors, separated by periods, while the `counter()` function inserts the value of the "subitem" counter. This creates a nested numbering system that indicates the level of each list item.

By using the `counter()` and `counters()` functions in your CSS styles, you can create dynamic and customizable numbering systems for lists and other content on your web pages.

Updated on