CSS Dot Leaders in Table of Content
Dot leaders are a row of dots that connect chapter titles to their corresponding page numbers, commonly found in table of content and index pages. Just like this:
And I think they’re pretty.
Here’s 2 ways to do it dynamically in CSS.
First thing first, let’s split them into 3 sections: left, dots and right:
<div class="entry">
<div class="left">Left</div>
<div class="dots"></div>
<div class="right">Right</div>
</div>
Now let’s make the container a flex box:
.entry {
display: flex;
width: 100%;
}
At current stage, the left and right texts are still sticking together. To push them to both sides, you need to set the dot container to the maximum width:
.dots {
width: 100%;
}
Since that they are inside a flex box, the widths will be adjusted automatically.
Now that the layout is set, we could start working on the dots.
Method 1: Radial Gradient
Imagine — first, we draw one single circle (a dot) in the background with radial-gradient. Then we have it repeat horizontally with background-repeat.
.dots {
width: 100%;
background: radial-gradient(circle at 50% 0.8em, #999 8%, transparent 8%);
background-size: 0.5em;
background-repeat: repeat-x;
}
And viola! Quick and easy.
The Pros
- Complete control over individual dot size and gaps.
The Cons
- Some dots may be cut in half.
- When zoomed in, the dots are not very sharp.
Method 2: Text and Overflow Clip
This may sound bizarre, but if you know how many dots will surely occupy that space, just type them in!
.dots {
height: 1em; /* very important */
overflow: hidden; /* very important */
word-wrap: break-word; /* where magic happens */
color: #999;
letter-spacing: 5px;
}
.dots:after {
content: '...........................................................';
}
The Pros
- No more half dots! Thanks to word-wrap: break-word which wraps overflowed dots to the next line (which is hidden).
- Crystal clear when zoomed in.
The Cons
- Less control over the appearance of the dots.
- You may get square dots depending on the font.
- If unlucky, you may not have enough dots to cover the area.
That's it, hope you like it!