CSS Counter
CSS counters are variables maintained by CSS that can be used to add automatic numbering to elements. These counters allow for dynamic content generation in HTML without the need for JavaScript. They are especially useful for lists, table rows, or any other type of content that requires numbering.
Key Points on CSS Counter:
- The
counter-reset
property initializes or resets the counter value. - The
counter-increment
property increments the counter by a specified value. - To display the counter, use
counter()
function. - CSS counters work in combination with elements like
::before
or::after
pseudo-elements. - The counter can be incremented based on element types such as
li
,h2
, etc. - Multiple counters can be used for nested elements, enabling hierarchical numbering.
Syntax for CSS Counter Properties:
Syntax Example
/* Reset counter */
counter-reset: counter-name value;
/* Increment counter */
counter-increment: counter-name value;
/* Display counter */
content: counter(counter-name);
Examples of CSS Counter Properties:
The following examples demonstrate the usage of different counter properties:
Code Example: Basic Counter Usage
ul {
counter-reset: item;
}
li {
counter-increment: item;
}
li::before {
content: counter(item) ". ";
}
Output
- First item
- Second item
- Third item
Code Example: Nested Counter Usage
ol {
counter-reset: section;
}
li {
counter-increment: section;
}
li::before {
content: "Section " counter(section) ": ";
}
Output
- Introduction
- Content
- Conclusion
Common Counter Properties:
- counter-reset: Resets or initializes a counter to a specified value. It is applied to a parent element.
- counter-increment: Increments a counter each time it is applied, usually on a list item or element.
- counter(): Used to display the value of a counter.
- content: This property can be used to insert the counter value before or after the element using pseudo-elements like
::before
or::after
.
CSS counters offer an efficient way to automate numbering in lists and other HTML structures. They're a lightweight solution for dynamic content generation without resorting to JavaScript.