Jayesh Bhoot's Ghost Town

How I use :has() selector to add table of contents

Posted on in , , ,

I show off a static site gen soupault, and my solution to add table of contents using CSS selectors

Copy-pasting my comment in a converstion on lobste.rs titled The Undeniable Utility Of CSS :has:

My most recent favourite use of :has was to target insertion of a table of contents (TOC) on pages of my website.

Assuming the following configuration for the static site generator I use (soupault):

[widgets.table-of-contents]
selector = "hgroup:has(h1)"
action = "insert_after"

the :has selector instructs soupault to only insert TOC in those pages which have an h1 heading, and to insert it right after the first hgroup of the page, so that the TOC is located right after the heading + subtitle + timestamp + tags combo.

:has is a selector best used judiciously though due to performance concerns. Firefox (and presumably other browsers) help by displaying a tortoise symbol to flag an unconstrained :has selector.