About
css supports counter variable 1) that can be used in a property value (for instance in a content property to add numbering to:
- or list
Example
List
For instance:
- We create two counters:
- one for the level 1
- one for the level 2
counter-set is not yet supported by Apple Safari
ol { counter-set: level1 }
ol > ol { counter-set: level2 }
- Styling to show the counter value
li { display: block }
ol li::before { content: counter(level1) ". "; counter-increment: level1 }
ol ol li::before { content: counter(level1) "." counter(level2, upper-roman) " "; counter-increment: level2 }
- The html
<ol>
<li> first item </li>
<li> second item </li>
<ol>
<li> second level, first item </li>
<li> second level, first item </li>
</ol>
<li> third item </li>
<li> fourth item </li>
</ol>
- The result:
Chapter and section
This example shows a way to number chapters and sections with “Chapter 1”, “1.1”, “1.2”, etc.
- The css
body {
counter-set: chapter 0 section 0; /* scope is on the body */
}
h1::before {
content: "Chapter " counter(chapter) ". ";
counter-increment: chapter 1; /* Add 1 to chapter */
counter-set: section 0;
}
h2::before {
content: counter(chapter) "." counter(section) " ";
counter-increment: section;
}
- The html
<h1>Chapter</h1>
<h2>Section</h2>
<h2>Section</h2>
<h2>Section</h2>
<h1>Chapter</h1>
<h2>Section</h2>
<h2>Section</h2>
<h2>Section</h2>
- Output:
Property
Nested Counter
Nested counter 4) are pretty wild if you don't understand their internal.
Counter:
- got an added extra internal id by scope (even if named)
- their scope/creation is created:
- explicitly with:
- the counter-set
- or counter-reset is called.
- implicitly with:
- the counter-increment if counter-set or counter-reset was not called before
For instance:
- We create an item counter, for all children ol of the body element
body > ol { counter-reset: item }
- We create / reset a new counter at the third ol descendant
body > ol > ol > ol { counter-reset: item }
- Styling to show the counter value
li { display: block }
li::before { content: counter(item) ". "; counter-increment: item }
- The html and the explanation in comment or text
<ol> <!-- item0 is created, set to 0 -->
<li> item0 is incremented to 1 </li>
<li> item0 is incremented to 2 </li>
<ol>
<li> item0 is incremented to 3 </li>
<li> item0 is incremented to 4 </li>
<ol> <!-- item1 is created, set to 0, nested in item0 -->
<li> item1 is incremented to 1 </li>
<li> item1 is incremented to 2 </li>
</ol>
<li> item1 is incremented to 3 and not item0 ! because their was no call to counter-set or reset</li>
</ol>
<li> item0 is incremented to 5 </li>
<li> item0 is incremented to 6 </li>
</ol>
<ol> <!-- item2 is created, set to 0 -->
<li> item2 is incremented to 1 </li>
<li> item2 is incremented to 2 </li>
</ol>
- The result: