I want to style the following HTML so that the chapter numbers go in sequence 1, 2, 3, even though the third number is in a different list than the first two.
<!DOCTYPE html>
<title>Continued Numbering</title>
<style>
ol.book-contents li {
list-style-type: upper-roman;
}
ol.book-contents ol li {
list-style-type: decimal;
}
</style>
<ol class="book-contents">
<li>Section One
<ol>
<li>Chapter One</li>
<li>Chapter Two</li>
</ol>
</li>
<li>Section Two
<ol>
<li>Chapter Three</li>
</ol>
</li>
</ol>
That is, I'd like the output to look like this:
I. Section One
1. Chapter 1
2. Chapter 2
II. Section Two
3. Chapter 3
Is there a way I can do this with CSS?
Here's a complete solution that uses the counter-reset
, counter-increment
, and content
properties to solve the continued number problem, and it uses the ::marker
pseudo-element to solve the formatting problem. Credit to rachelandrew for the ::marker
idea. There's no need for additional markup in the HTML (beyond the book-contents
class that was specified in the original question).
As you can see in the test, this CSS handles the troublesome tenth chapter, with (1) its multi-digit chapter number that aligns properly on its decimal and (2) its long name that wraps with the proper hanging indentation.
ol.book-contents {
counter-reset: chapter;
}
ol.book-contents li {
list-style-type: upper-roman;
}
ol.book-contents li ol li {
list-style-type: decimal;
counter-increment: chapter;
}
ol.book-contents li ol li::marker {
content: counter(chapter) '. ';
}
<!DOCTYPE html>
<title>Continued Numbering</title>
<ol class="book-contents">
<li>Section One
<ol>
<li>Chapter One</li>
<li>Chapter Two</li>
</ol>
</li>
<li>Section Two
<ol>
<li>Chapter Three</li>
<li>Chapter Four</li>
<li>Chapter Five</li>
<li>Chapter Six</li>
<li>Chapter Seven</li>
<li>Chapter Eight</li>
<li>Chapter Nine</li>
<li>Chapter Ten (shown so you can see its proper decimal alignment and its proper long-string wrapping behavior that honors the hanging indent)</li>
</ol>
</li>
</ol>