CSS Using Two Counters
Different levels of numbering can each have a counter of their own. Below, the page gets one counter (named "section"), and each <h1> element gets another (named "subsection").
Example
Prompt
Create a page with CSS counters that uses two counters: one named "section" reset on the body, and one named "subsection" reset on each h1. Use ::before pseudo-elements to prepend "Section X." before h1 headings and "X.Y" before h2 headings. Include several h1 and h2 elements to demonstrate the numbering.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Two Counters</title>
<style>
body {
counter-reset: section;
}
h1 {
counter-reset: subsection;
}
h1::before {
counter-increment: section;
content: "Section " counter(section) ". ";
}
h2::before {
counter-increment: subsection;
content: counter(section) "." counter(subsection) " ";
}
</style>
</head>
<body>
<h1>HTML Tutorial</h1>
<h2>HTML Introduction</h2>
<h2>HTML Editors</h2>
<h2>HTML Basic</h2>
<h1>CSS Tutorial</h1>
<h2>CSS Introduction</h2>
<h2>CSS Syntax</h2>
<h2>CSS Selectors</h2>
<h1>JavaScript Tutorial</h1>
<h2>JavaScript Introduction</h2>
<h2>JavaScript Variables</h2>
</body>
</html>
The CSS counters() Function
Nested counters of the same name can be read in one go: the counters() function gives back their current values as a string.
That same function also lets you place a string between the different levels.
Example
Prompt
Create a page with nested ordered lists where list-style-type is set to none. Use a CSS counter named "section" that resets on each ol, increments on each li, and uses the counters() function with a "." separator in the li::before content to display nested numbering like "1", "1.1", "1.1.1".
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS counters() Function</title>
<style>
ol {
counter-reset: section;
list-style-type: none;
}
li::before {
counter-increment: section;
content: counters(section, ".") " ";
}
</style>
</head>
<body>
<ol>
<li>Item
<ol>
<li>Item
<ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol>
</li>
<li>Item</li>
<li>Item</li>
</ol>
</li>
<li>Item
<ol>
<li>Item</li>
<li>Item</li>
</ol>
</li>
<li>Item</li>
</ol>
</body>
</html>
CSS Counter Properties
These CSS properties and functions work with counters:
- content - Inserts generated content, together with the
::beforeand::afterpseudo-elements. - counter-increment - Raises the value of one or more counters.
- counter-reset - Creates one or more counters, or resets them.
- counter() - Gives back the current value of the named counter.
- counters() - Gives back the current values of named and nested counters.