Responsive TOC leaders in CSS

Example of how to create those dotted lines and make all of it responsive.

Read the article for more details: Responsive table of contents leaders with CSS

Repository: https://github.com/asaaki/responsive-toc-leaders-in-css

Contents

A chapter title
01
Slightly longer title which needs to break into multiple lines to fit on the page
09
Another awesome chapter
23
Be more creative with your titles ;-)
42
Resize this box horizontally. ↘

Code

HTML


<div class="toc">
  <h2>Contents</h2>

  <div class="entry">
    <div class="chapter">A chapter title</div>
    <div class="page">01</div>
  </div>
  <div class="entry">
    <div class="chapter">Slightly longer title which needs to break into multiple lines to fit on the page</div>
    <div class="page">09</div>
  </div>
  <div class="entry">
    <div class="chapter">Another awesome chapter</div>
    <div class="page">23</div>
  </div>
  <div class="entry">
    <div class="chapter">Be more creative with your titles ;-)</div>
    <div class="page">42</div>
  </div>
</div>
      

CSS


.entry {
  display: grid;
  grid-template-columns: auto max-content;
  grid-template-areas: "chapter page";
  align-items: end;
  gap: 0 .25rem; /* customize the gap to your needs */
}

.chapter {
  grid-area: chapter;
  position: relative;
  overflow: hidden;
}

.chapter::after {
  position: absolute;
  padding-left: .25ch; /* customise the padding to your needs */
  /* adjust the amount of dots to your needs */
  content: " . . . . . . . . . . . . . . . . . . . "
    ". . . . . . . . . . . . . . . . . . . . . . . "
    ". . . . . . . . . . . . . . . . . . . . . . . "
    ". . . . . . . . . . . . . . . . . . . . . . . "
    ". . . . . . . . . . . . . . . . . . . . . . . ";
  text-align: right; /* optional, can be removed */
}

.page {
  grid-area: page;
}