CSS Counters
CSS counters let you number elements automatically using variables that CSS tracks and increments as it renders the page.
A counter is a variable maintained by CSS. You reset it to a starting value, increment it on each element you want to count, and print its value with the content property. This means numbering stays correct even when items are added or removed.
The Three Pieces
- counter-reset creates a counter and sets its starting value, usually on a parent
- counter-increment adds to the counter, usually on each item being numbered
- counter() prints the value, used inside the content of a ::before or ::after
Numbering Section Headings
Automatic section numbers
<!DOCTYPE html>
<html>
<head>
<style>
body {
counter-reset: section;
}
h2::before {
counter-increment: section;
content: counter(section) '. ';
color: #00643c;
font-weight: 700;
}
</style>
</head>
<body>
<h2>Getting Started</h2>
<h2>Installation</h2>
<h2>Usage</h2>
</body>
</html>Nested and Multi-level Counters
You can run several counters at once. The <counters()> function, with an s, joins every level of a nested counter with a separator, which is perfect for outlines like 1.1 and 1.2.
Outline numbering
<!DOCTYPE html>
<html>
<head>
<style>
ol {
counter-reset: item;
list-style: none;
}
ol li::before {
counter-increment: item;
content: counters(item, '.') ' ';
font-weight: 600;
}
</style>
</head>
<body>
<ol>
<li>Introduction
<ol>
<li>Background</li>
<li>Scope</li>
</ol>
</li>
<li>Methods</li>
</ol>
</body>
</html>Note: Counter numbers are generated content, so they are visual only. Do not rely on them to convey meaning that must be read by assistive technology or copied as text.
Note: Pass a second argument to counter() to change the style, for example counter(section, upper-roman) for I, II, III.
Exercise: CSS Counters
Which property initializes a CSS counter and sets its starting value?