Haar's Half Measure

What I talk about when I talk about physics.

06 Jan 2024

Adding a floating TOC

I’m using a theme called ‘Ink-free’. Pretty awesome I would say. I will make it even more awesome by adding a floating Table of Contents (TOC). Look to the right. Do you see it? If you don’t then probably I messed up somewhere. Anyway, here’s the process.

The default one

By default you already have one. But it is a static TOC, which does not make any sense. Look into the /layouts/_default/_markup/single.html folder. Here’s the code I have been using to generate a TOC.

{{ if and (gt .WordCount 400 ) (.Site.Params.toc) (ne .Params.toc false) }}
<aside class="toc">
    <header>
    <h1>Contents</h1>
    </header>
    {{.TableOfContents}}
</aside>
{{ end }}

For posts that exceed the 400 words limit, a specified true toc field in the front matter will result in a TOC. Now I would like to make this floats. Whatever floats the boat huh?

The modified one

Alright. Local pertubation only. First I’d like to figure out where I should put my TOC: I think next to the post section, same level as the post title would be perfect. To do this, let us create a grid.

We’ll have a thing called main-section to wrap all the post (from title to the beginning of footer).

<div class="main-section">
    <div class="post">
        ...
    </div>
</div>

and the div that will carry our TOC is a navigation class.

<div class="main-section">
    <div class="post">
        ...
    </div>
    <nav class="section-nav">
        {{ if and (gt .WordCount 400 ) (.Site.Params.toc) (ne .Params.toc false) }}
            <aside class="toc">
                <header>
                <h1>Contents</h1>
                </header>
                {{.TableOfContents}}
            </aside>
        {{ end }}
    </div>
</div>

Here’s the CSS that will reposition the TOC.

.main-section {
    display: grid;
    grid-template-columns: 100% 15em;
}

I sprinkle some more cherry decoration on the sundae

.section-nav {
    padding-left: 25px;
}

.toc {
    line-height: 1.7em;
    border-left: 5px solid #efefef;
    padding-left: 25px;
    
}

.toc a {
    color: #ccc;
}

.toc a:hover,
.toc a:focus {
  color: #666;
}

Lastly, the floating part. We want the navigation to floats along the main-section. Hence

.main-section > nav {
    position: sticky;
    top: 4rem;
    align-self: start;
  }

to be continued…

Next time, we'll talk about "10 ways how quantum computing will solve climate change."