CSS Counters CSS
- CSS Introduction
- CSS Selectors
- How To Add CSS
- CSS Colors
- CSS Backgrounds
- CSS Borders
- CSS Margins
- CSS Padding
- CSS Height and Width
- CSS Outline
- CSS Text
- CSS Fonts
- CSS Links
- CSS Lists
- CSS Tables
- CSS Layout - The display Property
- CSS Layout - CSS position
- CSS Layout - display: inline-block
- CSS Layout - Horizontal & Vertical Align
- CSS Combinators
- CSS Opacity / Transparency
- CSS Dropdowns
- Image Gallery
- CSS Attribute Selectors
- CSS Counters
- CSS Media Queries
CSS Counters
Automatic Numbering With Counters
CSS counters are like "variables". The variable values can be incremented by CSS rules (which will track how many times they are used).
To work with CSS counters we will use the following properties:
counter-reset
- Creates or resets a countercounter-increment
- Increments a counter valuecontent
- Inserts generated contentcounter()
orcounters()
function - Adds the value of a counter to an element
To use a CSS counter, it must first be created with counter-reset
.
The following example creates a counter for the page (in the body selector), then increments the counter value for each <h2> element and adds "Section <value of the counter>:" to the beginning of each <h2> element:
Example
body {
counter-reset: section;
}
h2::before {
counter-increment: section;
content: "Section " counter(section) ": ";
}
Nesting Counters
Let's take an example of nested counter
Example
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) " ";
}
Make outlined lists
A counter can also be useful to make outlined lists because a new instance of a counter is automatically created in child elements. Here we use the counters()
function to insert a string between different levels of nested counters:
Example
ol {
counter-reset: section;
list-style-type: none;
}
li::before {
counter-increment: section;
content: counters(section,".") " ";
}
CSS counter-reset Property
Create a counter ("my-sec-counter") and increase it by one for each occurrence of the <h2> selector:
Example
body {
/* Set "my-sec-counter" to 0 */
counter-reset: my-sec-counter;
}
h2::before {
/* Increment "my-sec-counter" by 1 */
counter-increment: my-sec-counter;
content: "Section " counter(my-sec-counter) ". ";
}
The counter-reset
property creates or resets one or more CSS counters.
The counter-reset
property is usually used together with the counter-increment property and the content property.