jamespants.com Blog

Living C.L.E.A.N.E.R.

(CSS that is Lowkey Exquisite with Assuredly No Extraneous React) Story pages that run on stylesheets alone

Chapter 1 Introduction §

While I always aspire to be at the vanguard of the new, I must regretfully admit that I have been sleeping a bit on the latest in the CSS world — mostly because I’ve been writing TypeScript and such. I currently own a CMS at Bloomberg used to create interactive feature articles, which is mostly built on WebSockets, permission systems, streaming, portable components, in-browser IDEs, etc. It’s cool, but I’ve been so lost in my own script sauce, that I failed to look around at the supremely fresh and low-hanging fruit surrounding me in the stylesheet realm. There is a plethora of options right now for adding interactivity to a page that require no scripting whatsoever, and I am aiming to collect as many of these flavors as possible in my little tool chest. Therefore, this page is an attempt to learn these CSS features by implementing a somewhat contrived kitchen-sink article using mushroom-related data from my iNaturalist account, and walking through a handful of them. Hopefully it’s useful.

One note on the plumbing before we start. The stylesheets used here are sorted into Cascade layer A named group of styles. Rules in a later layer win over rules in an earlier one, regardless of selector specificity. with @layer CSF, and written with native nesting CSF. Both have been stable in every major browser for a few years now, so I won’t dwell on them. But in general, between them, there is little reason to be reaching for Sass or PostCSS anymore.

Chapter 2 Layout §

First off, every element on this page sits inside one grid. In many article cases, this works well. Instead of doing like a 12-col thing, I’m using grid-template-columns with named grid lines. This way, any individual HTML element only declares which column it belongs in, such as main or wide, and the CSS decides where that column is at each screen width. This chapter shows how the page’s template is built, lets you try your own, then deals with the one thing a grid can’t do super well, which is floats.

Fly agaric, Amanita muscaria, Skagway, Alaska, August 2023. The storybook toadstool: a red cap scattered with white warts. This figure runs across the wide area with its caption in rail, two of the columns described below. Drawn in ASCII from a photograph by jsingleton20 / iNaturalist

Grid and subgrid§

The page layout is a single grid with five named areas, allowing each child element to be placed by name instead of by column number. The diagram below draws each area and what it’s for.

Each chapter passes the same columns down to its children with subgrid CSF, so nested elements still will line up with the page grid. The diagram is a subgrid too, so it shows the page’s real columns at the current window size.

I find the named grid column syntax a bit obtuse, and am still getting the hang of it, but here is an example:

fullgrid-column: full

Runs edge to edge. Useful for full-bleed media and such.

widegrid-column: wide

Covers the text and the rail plus some space on either side. The photo grid and a good chunk of the code blocks use it.

maingrid-column: main

The reading column for body text.

railgrid-column: rail

A narrow column beside the text for notes and captions. The figure captions and the sidenote in Chapter 3 sit in it.

navgrid-column: nav

Holds the chapter list, on desktop only.

The five areas, drawn on the page grid. Below 84.5rem there isn’t room for a rail, so it moves under the text column. Below 58.5rem the nav is hidden and the side columns shrink to a small margin.
page.css CSS
.page {
  display: grid;
  grid-template-columns:
    [full-start nav-start] var(--nav-width)
    [nav-end] 1fr
    [wide-start] minmax(0, var(--wide-slack))
    calc(var(--gutter) + var(--rail))
    [main-start] minmax(0, var(--measure))
    [main-end] var(--gutter)
    [rail-start] var(--rail)
    [rail-end] minmax(0, var(--wide-slack))
    [wide-end] 1fr
    var(--nav-width)
    [full-end];
}

nav {
  grid-column: nav;
}

.chapter {
  display: grid;
  grid-template-columns: subgrid;
}

.chapter > * {
  grid-column: main;
}
.chapter > .wide {
  grid-column: wide;
}
.chapter > .full {
  grid-column: full;
}
.chapter > .rail {
  grid-column: rail;
}

/* No room for a rail: it shares main's lines, so rail items stack under the text */
@media (width < 84.5rem) {
  .page {
    grid-template-columns:
      [full-start nav-start] var(--nav-width)
      [nav-end wide-start] minmax(0, 1fr)
      [main-start rail-start] minmax(0, var(--measure))
      [main-end rail-end] minmax(0, 1fr)
      [wide-end] var(--nav-width)
      [full-end];
  }
}
A pair of lines such as rail-start and rail-end defines an area you can refer to as rail. See named grid lines.

A few things about the CSS above that aren’t obvious at first glance:

  • The areas nest. wide starts on the line before main and ends on the line after rail, so anything wide covers both. full covers everything.
  • main stays centered because the unnamed track before it is exactly as wide as the gutter plus the rail after it.
  • A rail item lands in the same row as whatever comes right before it, since the grid drops it into the next free cell to the right. So put the note straight after its paragraph in the HTML.
  • wide maxes out at 1280px, and each side of it gets a minmax(0, …) track capped at half the leftover space which the browser fills before it adds anything to the 1fr tracks. Beyond the cap, the extra width goes to the 1fr tracks outside wide.
  • Going responsive only means renaming lines. Below 84.5rem, the media query puts rail-start and main-start on the same line.

B.Y.O.G (Bring Your Own Grid)§

You can try this all out. Type any value for grid-template-columns below, or start from a preset. The first is this page’s own grid, with its custom properties written out as values. The preview is a real grid, so it shows the widths the browser works out for each track at the current window size. You can name a pair of lines like name-start and name-end and the CSS will include a rule to place children in that area.

Presets
grid.css
.grid {
  display: grid;
  grid-template-columns:
    [full-start nav-start] 140px
    [nav-end] 1fr
    [wide-start] minmax(0, clamp(0px, (100% - 280px - 66rem) / 2, 112px)) calc(2rem + 11rem)
    [main-start] minmax(0, 40rem)
    [main-end] 2rem
    [rail-start] 11rem
    [rail-end] minmax(0, clamp(0px, (100% - 280px - 66rem) / 2, 112px))
    [wide-end] 1fr 140px
    [full-end];
  column-gap: 0;

  > .full { grid-column: full; }
  > .nav { grid-column: nav; }
  > .wide { grid-column: wide; }
  > .main { grid-column: main; }
  > .rail { grid-column: rail; }
}
.grid {
  display: grid;
  grid-template-columns:
    [full-start] minmax(1rem, 1fr)
    [wide-start] minmax(0, 8rem)
    [main-start] minmax(0, 40rem)
    [main-end] minmax(0, 8rem)
    [wide-end] minmax(1rem, 1fr)
    [full-end];
  column-gap: 0;

  > .full { grid-column: full; }
  > .wide { grid-column: wide; }
  > .main { grid-column: main; }
}
.grid {
  display: grid;
  grid-template-columns:
    [story-start] minmax(0, 1fr)
    [story-end related-start] 18rem
    [related-end];
  column-gap: 2rem;

  > .story { grid-column: story; }
  > .related { grid-column: related; }
}
.grid {
  display: grid;
  grid-template-columns:
    [left-start] 1fr
    [left-end lead-start] 2fr
    [lead-end right-start] 1fr
    [right-end];
  column-gap: 1.5rem;

  > .left { grid-column: left; }
  > .lead { grid-column: lead; }
  > .right { grid-column: right; }
}
.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  column-gap: 1rem;
}
.grid {
  display: grid;
  grid-template-columns:
    [main-start] 1.618fr
    [main-end aside-start] 1fr
    [aside-end];
  column-gap: 0;

  > .main { grid-column: main; }
  > .aside { grid-column: aside; }
}
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  column-gap: 1rem;
}
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr));
  column-gap: 0.75rem;
}

Dealing with floats§

While the grid decides where each block goes, inside a block, the text still flows the old way, so a picture can float in the reading column with the text running around it, with the caveat that the floated content must be wrapped in a parent. This means CMSs that spit out an array of stacked items need special handling to wrap in a shared div when items must be floated.

Anyway, the ASCII morel mushroom above uses float: inline-start CSF, which means the start of the line: left in English, right in a right-to-left language. A circular clip-path crops it, and shape-outside: circle() CSF makes the text follow the same circle instead of the drawing’s square box. (I always have to look this up.) shape-margin sets a margin matching the CSS shape around the item. Finally, the wrapper is declared withdisplay: flow-root so that the float stays inside it even when the text beside it is short. A container query stops the float when the column is too narrow for text on both sides.

American yellow morel, Morchella americana, drawn in ASCII.

float.css CSS
.wrap {
  display: flow-root; /* holds the float */
  container-type: inline-size;
}

/* The wrapper is the grid item, so the drawing can float inside it */
.wrap__photo {
  float: left; /* fallback */
  float: inline-start;
  inline-size: 40%;
  aspect-ratio: 1;
  object-fit: cover;
  clip-path: circle(50%);
  shape-outside: circle(50%) border-box;
  shape-margin: 1.25rem;
  margin-inline-end: 1.25rem;
}

@container (width < 24rem) {
  .wrap__photo {
    float: none;
    margin-inline: auto;
  }
}
The text can only wrap as far as the float’s margin box, so the margin has to be at least as wide as shape-margin.

Chapter 3 Scroll effects §

This article makes heavy use of CSS scroll effects, which used to require JavaScript, and would be really easy to screw up. For example, you could add a scroll listener to do something benign, but it would actually recalculate styles on every frame and would absolutely wreck page performance. Intersection Observer helped quite a bit (and still does, actually), but for a lot of stuff you may see on NYT or Bloomberg now, using scroll-driven animations CSF can be really powerful, letting CSS link an animation to scroll position instead of JS. You write normal @keyframes, then set animation-timeline. This allows the animation to progress as the page scrolls naturally. There are two types of timeline that can be used. A scroll timeline follows the scroll position of a container. A view timeline follows an element’s position as it moves through the viewport.

The progress bar at the top of the screen is the simplest example. It is a 2px-tall element with scale: 0 1 as its starting keyframe and animation-timeline: scroll(root). The animation is at 0% at the top of the page and 100% at the bottom.

Here is the code:

progress.css CSS
@keyframes progress-grow {
  from {
    scale: 0 1;
  }
}

.progress {
  position: fixed;
  inset: 0 0 auto;
  height: 2px;
  background: var(--accent);
  transform-origin: left center;
  scale: 0 1; /* hidden in browsers without scroll timelines */
}

@supports (animation-timeline: scroll()) {
  .progress {
    scale: 1 1;
    animation: progress-grow linear both;
    animation-timeline: scroll(root);
  }
}
The keyframes only give a starting point, so the bar grows to its normal scale: 1 1. animation-timeline comes after the animation shorthand, because the shorthand resets it.

Intro animation§

The header animation looks difficult, but like all timeless elegance, is alarmingly simple to pull off. The header itself is 200svh tall, and its contents sit in a 100svh box with position: sticky; top: 0, which causes the header to stay put for one screen’s worth of scrolling, giving us ample scrollspace to let the animations play during that time.

The header declares a named view timeline, view-timeline-name: --header-scroll CSF, and its children use it with animation-timeline: --header-scroll. Each animation is limited to part of the timeline with animation-range CSF. The contain range covers the period during which the header fills the viewport, which is exactly the time the sticky box is pinned.

At the time of writing, Firefox doesn’t support these scroll animations, so it (and any other browser without them) just gets the title sitting still in a 100svh header, for the committed fanbase.

header.css CSS
header {
  height: 200svh;
  view-timeline-name: --header-scroll;
}

.header__inner {
  position: sticky;
  top: 0;
  height: 100svh;
}

/* Only a "to" keyframe: each letter starts in its place in the title */
@keyframes explode {
  to {
    transform: translate(var(--x), var(--y)) rotate(var(--spin));
    opacity: 0;
  }
}

.header__letters > span {
  --i: calc(sibling-index() - 1);
  --angle: calc(var(--i) * 137.508deg);
  --reach: calc(30vmax + mod(var(--i) * 7, 5) * 10vmax);
  --x: calc(cos(var(--angle)) * var(--reach));
  --y: calc(sin(var(--angle)) * var(--reach));
  --spin: calc((mod(var(--i) * 53, 360) - 180) * 1deg);
  --delay: calc(mod(var(--i) * 3, 7) * 3%);

  display: inline-block;
  animation: explode ease-in both;
  animation-timeline: --header-scroll;
  animation-range: contain var(--delay) contain calc(75% + var(--delay));
}
Simplified from the page’s CSS, which also numbers the letters by hand for browsers without sibling-index().

The title is split into one <span> per letter, with the whole title in a visually hidden span beside them, so screen readers read it as words rather than letter by letter. On load the letters sit in an ordinary line, centered via flex in an otherwise empty screen. The explode keyframes only define a to state only so the animation uses the element’s own value as a starting point. Each letter animates from its place in the title out to wherever its --x, --y and --spin send it, fading as it goes.

The cool thing here is that each letter works out its own direction, with no custom numbered classes (although you do still have to wrap them in span tags). sibling-index() CSF gives each letter a position, i. We multiply that by 137.5°, the golden angle, which spreads the letters around a circle so neighbors head off in wildly different directions, and cos() and sin() CSF turn the angle into a distance horizontally and vertically. mod() CSF scrambles the rest somewhat randomly: how far each letter goes, how much it spins and how late it leaves. In this case, multiplying i by a number and keeping the remainder (modulo operation) gives a value that jumps around instead of climbing steadily, which is close enough to random for this. (There is also the very recent random operation available now.)

The --delay pushes each letter’s animation-range back by up a little bit, so they don’t all leave at once, and ease-in makes each one transition slowly before they start flying. The last letters are gone by the end of the pinned scroll, just before the header itself scrolls away.

Animating numbers§

663

fungi logged on iNaturalist by me, out of 823 observations in all, as of October 2026.

As you may have noticed, the contrived number above counts up when it scrolls into view. CSS can’t normally animate a custom property, because it treats the value as an untyped string. Registering the property with @property CSF as an <integer> gives it a type the browser can interpolate, from 0 to 663. The target value comes from the HTML: attr() CSF with a type reads data-value="663" as an integer. A CSS counter displays the current value. One word of caution here I only recently discovered is that these custom property interpolations run on the CPU, which will cause a style recalculation, so use wisely.

stats.css CSS
@property --num {
  syntax: "<integer>";
  inherits: false;
  initial-value: 0;
}

@keyframes count-up {
  from {
    --num: 0;
  }
  to {
    --num: var(--to);
  }
}

.stat__num {
  --to: attr(data-value type(<integer>), 0);
  counter-reset: n var(--num);
  animation: count-up cubic-bezier(0.1, 0.6, 0.2, 1) both;
  animation-timeline: view();
  animation-range: entry 40% cover 50%;

  &::after {
    /* counter(n) prints the current --num as text, since content can't show a number directly.
       "/" starts the alt text: "" is empty, so screen readers skip the ticking digits */
    content: counter(n) / "";
  }
}
/ "" gives the generated digits empty alternative text. Screen readers read the static number in the HTML instead, which is visually hidden.
Observations per year Everything jsingleton20 logged on iNaturalist, by date observed
  1. 202167
  2. 2022330
  3. 2023257
  4. 202497
  5. 202534
  6. 202634

Here’s another one: each bar’s width comes from its data-value attribute, read with typed attr(). The bars start growing one after another because each bar offsets its animation-range by its sibling-index(). The list is a three-column grid, and each row uses grid-template-columns: subgrid, so the label and value columns line up across all rows. Safari doesn’t support typed attr() yet, so it gets each bar’s width from a hand-numbered :nth-child() fallback instead.

Mushrooms logged per month Fungi jsingleton20 logged on iNaturalist by date observed, one line per year
Fungi logged per month, by year
Month20222023202420252026
January1210000
February42000
March915211
April1516720
May387590
June27121623
July134516811
August11531627
September5040527
October418200
November270000
December155000

The line chart draws itself the same way. A build script pulls the monthly counts from iNaturalist and writes each year as one SVG <path>. The SVG uses preserveAspectRatio="none" so it stretches to fill its box, and vector-effect: non-scaling-stroke keeps the lines 2px thick with even dashes when it does. A clip-path: inset() on a view() timeline uncovers the lines from left to right. The labels, axis and hover tips are plain HTML on top, so the stretching doesn’t squash the text. Hovering a month shows a tip, which is just display: block on :hover.

Animating ASCII§

Many of the mushroom images on this page aren’t actually images, and no script runs to animate them. Instead, each one is plain ASCII text in a <pre> tag, and animation steals the age-old mechanics of a flipbook to make them move.

A lil Node script using the sharp library draws each mushroom out of a few rough 3D shapes, lights them from the upper left, and swaps each patch of light for a character from an array of unicode like .:-=+*#%@, so the most lit parts get the heaviest marks. It does this at build time, once per frame, turning the mushroom a little each time.

All the frames then go into one <pre> in a big stack. The morel mushroom, for example, is 29 lines tall, so lines 1 to 29 are frame 1, lines 30 to 58 are frame 2, etc. Since every frame is the same height, we can use the <pre> tag like a film strip by placing it in a container exactly one frame tall with overflow: hidden, so only one frame shows at a time.

morel.html HTML
<div
  class="ascii"
  role="img"
  aria-label="ASCII drawing of a morel…"
  style="--cols: 48; --rows: 29; --frames: 8"
>
  <div class="ascii__window" aria-hidden="true">
    <pre class="ascii__reel">
                     =-=-:.
                    +=+==-:.
                  +***-*+:=-..
                 *%#=##++++:-:.
                 …the rest of frame 1, then frames 2 to 8 under it…
    </pre>
  </div>
</div>
Trimmed from morel.html. Screen readers get the aria-label, and skip the characters. The real file writes each line break as &#10;, so the whole reel is one line of HTML.

The actual trick is stupid simple. To advance to the next frame, you just move the reel by exactly one frame height. With line-height: 1, each line is 1em tall, so a 29-line frame is 29em, and the whole 8-frame reel is 232em. To show frame 2, the reel moves up 29em. To show frame 3, it moves up 58em:

reel.txt TEXT
lines   1–29    frame 1   translate: 0
lines  30–58    frame 2   translate: 0 -29em
lines  59–87    frame 3   translate: 0 -58em
…
lines 204–232   frame 8   translate: 0 -203em
Each frame starts one frame height further down the reel, so it moves up by that much each time.

But because we are using the CSS language to the fullest extent of taste, we don’t actually need to write 29em in the code. Instead, we simply translate the reel up by -100% over discrete steps.

ascii.css CSS
@keyframes ascii-reel {
  to {
    translate: 0 -100%;
  }
}

/* <div class="ascii" style="--cols: 96; --rows: 40; --frames: 8"> */
.ascii {
  container-type: inline-size;
}

.ascii__window {
  /* the widest line fills the box: a monospace character is a little over 0.6em wide */
  font-size: calc(100cqi / (var(--cols) * 0.61));
  block-size: calc(var(--rows) * 1em);
  overflow: hidden;
}

.ascii__reel {
  line-height: 1;
  white-space: pre;
  animation: ascii-reel calc(var(--frames) * 0.5s) steps(var(--frames)) infinite;
}
Trimmed from ascii.css. Each drawing passes its own size and frame count in the style attribute, so one set of rules animates them all.

We use steps here, because by default, using a translation like this would scroll the frames smoothly and linearly, which wouldn’t work for flipbook-style animations. Using steps() CSF, we can turn the slide into a proper flipbook by making discrete frame-like “step” moves in the translation. For example, steps(8) cuts the animation into 8 equal jumps, and holds each position until the next one. Eight equal jumps across a reel 8 frames tall are one frame each: 232em ÷ 8 = 29em, which, lo and behold, is the same 29em we calculated earlier. Since normally, the last jump would land on -100%, past the final frame, steps() thoughtfully ends each loop just before that last jump, so frame 8 holds, and the next loop starts again at frame 1. Cool.

To be clear, animating ASCII like this is not the best approach. We should probably use canvas here. Right now, every frame is in the HTML, so the bytes can add up. A <canvas> would draw the same thing from a few lines of script, but then there would be a script, right?

The chapter nav§

Now we move on to the meta scroll-driven animations. If you’re lucky enough to be on a desktop right now, you will notice the bars in the left margin show progress through each chapter and each chapter declares its own view timeline. The nav isn’t an ancestor of the chapters, so it can’t normally see those timelines. But now it can! timeline-scope CSF on the page wrapper makes them available to all of its descendants. The nav stays hidden until it sticks to the top of the viewport, using a scroll-state(stuck: top) CSF container query.

page.css CSS
/* Each chapter names its own view timeline, and the page wrapper shares them */
.chapter:nth-of-type(1) {
  view-timeline-name: --ch-1;
}
/* …and so on for each chapter */

.page {
  timeline-scope: --ch-1, --ch-2, --ch-3; /* … */
}

/* The bar's fill is a typed percentage, so it can animate */
@property --read {
  syntax: "<percentage>";
  inherits: false;
  initial-value: 0%;
}

@keyframes read {
  to {
    --read: 100%;
  }
}

nav a::before {
  background: linear-gradient(
    to right,
    currentColor var(--read),
    transparent 0
  );
  animation: read linear both;
  animation-range: contain 0% contain 100%;
}

nav li:nth-child(1) a::before {
  animation-timeline: --ch-1;
}

/* Hidden until it sticks to the top */
nav {
  position: sticky;
  top: 0;
  container-type: scroll-state;
}

@container scroll-state(stuck: top) {
  nav ol {
    opacity: 1;
  }
}
Trimmed from page.css and nav.css. The real nav repeats the animation-timeline rule for every chapter, and starts its list at opacity: 0.

The bar for the chapter you’re reading also darkens and lengthens. scroll-target-group: auto CSF turns the nav into a group of scroll markers where every link whose href points to an element on the page tracks that element. This is literally like two lines of CSS now. As you scroll, the browser picks the link whose target is currently in view, and :target-current CSF matches it. Previously, you had to make a scroll spy with an IntersectionObserver for this, toggling a class from JS. Life is crazy.

nav.css CSS
nav {
  scroll-target-group: auto;
}

nav a:target-current {
  opacity: 1;
}
Each link already points to its chapter (href="#layout"), which is all the browser needs to know which one is current.

The top bar§

For browsers with support, scroll back up a little and a bar with the page title and chapter links slides in at the top of the screen. Scroll down and it slides away. The root element is a scroll-state container, and the query scroll-state(scrolled: top) CSF matches when its most recent scroll was upward. Cool.

topbar.css CSS
:root {
  container-type: scroll-state;
}

.topbar {
  position: fixed;
  inset: 0 0 auto;
  color: white;
  mix-blend-mode: difference;
  translate: 0 -100%;
  transition: translate 0.4s var(--ease);
}

/* The page's most recent scroll was upward */
@container scroll-state(scrolled: top) {
  .topbar {
    translate: 0 0;
  }
}
In browsers without scroll-direction queries the bar stays hidden, except when a keyboard user tabs into it, which reveals it with :focus-within.

Parallax and photo essay§

Ringless honey mushrooms, Desarmillaria caespitosa, crowding an old stump in West Orange, New Jersey, September 2023. The drawing drifts on its frame’s view timeline. Drawn in ASCII from a photograph by jsingleton20 / iNaturalist
parallax.css CSS
@keyframes drift {
  from {
    translate: 0 -40%;
  }
  to {
    translate: 0 0;
  }
}

.figure__frame {
  height: min(60vh, 45vw);
  overflow: hidden;
  view-timeline: --frame;
}

@supports (animation-timeline: view()) {
  .ascii {
    animation: drift linear both;
    animation-timeline: --frame;
  }
}
Trimmed from figures.css. The frame is a short window with overflow: hidden, and the drawing slides down as the frame crosses the screen, so it seems to move slower than the page.

As a disclaimer, I’m not a huge fan of parallax, as it was thoroughly abused in the mid-’10s and I still recoil, but for demonstration purposes, we are doing it here. The drawing above is much taller than its frame. On the frame’s view timeline, it moves by translate from -40% to 0, so it scrolls noticeably slower than the page.

The photo essay below pins each photo with position: sticky. Each frame overlaps the previous one, so the next photo slides up over the current one. This works in every browser. In browsers that support scroll-driven animations, an @supports block increases the overlap and fades each new photo in. The captions describe each step.

A crown-tipped coral fungus branching up from a fallen log

01 — Pin

Each photo lives in a frame three screens tall, and pins to the top with position: sticky while its frame scrolls past. Crown-tipped coral fungus, West Orange, New Jersey, June 2024.

A bright yellow Tremella jelly fungus on a bare branch

02 — Fade

The image frames overlap with a negative margin, and where animation-timeline: view() is supported, the next photo fades in once it gets pinned. Tremella jelly fungus, West Orange, New Jersey, March 2023.

A painted suillus turned over to show its yellow pores, beside a second cap

03 — Curtain

Browsers without animation-timeline, which for now means Firefox, get a smaller overlap instead, so the next photo slides up over this one like a curtain. It’s not quite as elegant as the fade, but workable. Painted suillus, Gilboa, New York, August 2023.

A white coral fungus, like a small sea sponge, among dead leaves

04 — Frosted glass

This card is frosted glass: backdrop-filter: blur() over a see-through color-mix(). The last frame is shorter, so the photo lets go soon after. White coral fungus, Stamford, New York, August 2023.

essay.css CSS
@keyframes frame-in {
  from {
    opacity: 0;
  }
}

.essay {
  --frame: 300svh; /* how long each photo stays pinned */
  --overlap: 100svh; /* how far each frame slides up over the last */
}

.essay__frame {
  height: var(--frame);
  view-timeline-name: --frame;

  & + & {
    margin-block-start: calc(-1 * var(--overlap));
  }
}

.essay__pin {
  position: sticky;
  top: 0;
  height: 100lvh;
}

@supports (animation-timeline: view()) {
  .essay {
    --overlap: 200svh;
  }

  .essay__frame:not(:first-child) .essay__img {
    animation: frame-in linear both;
    animation-timeline: --frame;
    /* from when the frame's top reaches the top of the screen, half a screen later */
    animation-range: cover 100svh cover 150svh;
  }
}
Trimmed from essay.css, without the captions and the frosted-glass card. Each frame names its own --frame timeline, so each photo fades on its own frame’s scroll.

Again, because adopting the C.L.E.A.N.E.R. lifestyle involves extending the aesthetic goodwill to ALL users, every animation on the page is turned off for folks who have enabled reduced motion by ending each feature with a @media (prefers-reduced-motion: reduce) CSF block to remove animation.

Chapter 4 Interactive features §

Figures sized from an attribute§

You can size figures somewhat arbitrarily based on data attributes now. The figure below has data-span="wide" in its HTML and no modifier class. The CSS reads the attribute with typed attr() and passes it to if() CSF, an inline conditional, which chooses the grid column. While this is a somewhat unnecessary example, the point is that it opens up the magical realms of conditional logic in CSS.

Eastern North American destroying angel, Amanita bisporigera, Gilboa, New York, August 2023. Pure white, and among the deadliest mushrooms in North America. Drawn in ASCII from a photograph by jsingleton20 / iNaturalist

On wide screens, the caption is placed in the rail, aligned to the bottom of the drawing. As already mentioned, the figure makes judicious use of grid-template-columns: subgrid to take on the page columns, places the drawing across wide-start / main-end, and places the caption in rail. For folks on their phone in the subway, the caption goes below the drawing.

figures.css CSS
.figure {
  --span: attr(data-span type(<custom-ident>), main);
  grid-column: if(
    style(--span: full): full; style(--span: wide): wide; else: main
  );
}

/* The same result for browsers without if() */
@supports not (color: if(else: red)) {
  .figure[data-span="wide"] {
    grid-column: wide;
  }
  .figure[data-span="full"] {
    grid-column: full;
  }
}

Masonry and lightbox things§

The photo grid below is a masonry layout: items of different heights are packed into columns without gaps. It uses display: grid-lanes CSF, with Firefox’s earlier grid-template-rows: masonry syntax as a fallback, and a regular grid for browsers that support neither. Each photo is a button that opens a full-screen <dialog>. The dialogs section below explains how it opens without JavaScript. Enjoy some hard-to-discern pictures of mushrooms I took.

figures.css CSS
.mosaic {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.75rem;

  @media (width >= 48rem) {
    grid-template-columns: repeat(3, 1fr);
  }
}

/* Without masonry, photos are cropped to fill equal cells */
.mosaic img {
  height: 100%;
  object-fit: cover;
}

/* Firefox's earlier syntax */
@supports (grid-template-rows: masonry) {
  .mosaic {
    grid-template-rows: masonry;
  }
  .mosaic img {
    height: auto;
  }
}

/* The new standard */
@supports (display: grid-lanes) {
  .mosaic {
    display: grid-lanes;
  }
  .mosaic img {
    height: auto;
  }
}
Trimmed from figures.css. grid-lanes reuses grid-template-columns, so the same two or three columns become lanes, and each photo goes into whichever lane is shortest. With masonry on, the photos keep their own heights.

In the lightbox, the photo is shown with object-fit: contain CSF so it isn’t cropped. Behind it, a second copy uses object-fit: cover with filter: blur(40px) to fill the rest of the screen, which is a technique I lifted, but I forgot from where. (Great artists steal.)

A pure CSS carousel is now a thing you (mostly) can do. The carousel below is a horizontally scrolling list with scroll snapping CSF, and includes CSS-generated controls. The dots come from ::scroll-marker-group and ::scroll-marker CSF. The arrows are ::scroll-button(left) CSF and ::scroll-button(right), positioned over the image with anchor positioning, and disabled automatically at each end. Each caption becomes fully opaque when its slide snaps into place, through a scroll-state(snapped: x) CSF container query.

The carousel sets overflow: auto hidden rather than just overflow-x: auto because setting only overflow-x makes the browser compute overflow-y as auto as well, oddly. The captions are offset by a small translate, which makes the content a few pixels taller than the carousel. The carousel then becomes vertically scrollable and captures mouse-wheel scrolling over it. Setting overflow-y to hidden prevents this.

The comparison table§

The table below compares five of the most frequently recorded species in the iNaturalist data for my mushroom finds. The column headers themselves are sticky, so they stay visible while the table scrolls. On phones, the table scrolls horizontally inside its own container, with the row headers pinned on the left. The right edge fades out while there is more content to scroll to. The fade is a scroll-driven animation on a registered --fade-end length variable, so it disappears when you reach the end.

Five mushrooms, by the records From jsingleton20’s iNaturalist observations, as of October 2026.
Hen of the woodsGrifola frondosa Destroying angelAmanita bisporigera Scaly shieldPluteus petasatus White-pored chickenLaetiporus cincinnatus Red chanterelleCantharellus cinnabarinus
Records
ObservationsTotal logged 8 8 8 7 6
Research gradeaConfirmed by the community 6 0 4 5 4
Season
First foundMonth and year Oct2021 Sep2021 Jun2022 Sep2021 Aug2021
Most recentMonth and year Sep2026 Sep2023 Sep2023 Jun2026 Sep2026
Busiest monthMost finds Oct Sep Jun Jun Aug/Sep
Range
TownsbDifferent places found 4 6 3 4 4
StatesUS states 1 3 3 1 2
  1. On iNaturalist, an observation becomes research grade once the community agrees on its identification.
  2. Counted from the place name on each observation.

Hovering a row highlights it, and hovering a cell also highlights its column. CSS has no column selector for this, so the table uses :has(): .compare__table:has(td:nth-child(3):hover) matches the table while any cell in the third column is hovered, and then styles every cell in that column.

Popovers and anchor positioning§

The menus, tooltips and dialogs on this page are opened and closed by purely by HTML attributes, which is the proper way to use the platform. The settings menu is declared using the popover CSF attribute, which allows it to be opened by a button with a matching popovertarget. That’s really it. The browser handles opening, closing, the Escape key and clicks outside for us. We can position it near the target using anchor positioning CSF: position-area: block-end span-inline-start, which places it below the button, aligned to its edge, and position-try-fallbacks: flip-block CSF moves it above the button when there isn’t enough space below. The glossary definition in the introduction uses popover="hint" CSF with the interestfor attribute CSF, which allows it to open it on hover or focus. You can set the delay with interest-delay-start.

Dialogs§

The little button below opens a <dialog> using commandfor="…" command="show-modal" CSF. No JS, of course. The one annoyance is animating it, since a closed dialog is display: none, and transitions don’t typically run from display: none. You can mostly get around that with @starting-style CSF, which tells the browser what the entry transition starts from. By tacking allow-discrete CSF onto the display and overlay transitions (display 0.6s allow-discrete) we can keep the dialog visible (and in the top layer) until the exit transition is done. And as a nice bonus, closedby="any" CSF lets a click outside the dialog close it, along with the Escape key.

modal.css CSS
.modal {
  opacity: 0;
  translate: 0 2rem;
  transition:
    opacity 0.6s var(--ease),
    translate 0.6s var(--ease),
    overlay 0.6s allow-discrete,
    display 0.6s allow-discrete;
}

.modal[open] {
  opacity: 1;
  translate: 0 0;
}

/* Where the entry transition starts */
@starting-style {
  .modal[open] {
    opacity: 0;
    translate: 0 2rem;
  }
}

/* Stop the page scrolling while the dialog is open */
html:has(.modal[open]) {
  overflow: hidden;
}
The nice part is you don’t write a separate closing animation. The dialog just transitions back to its closed styles.

Accordions§

The accordion below is three <details> elements with the same name attribute CSF, so only one can be open at a time. Each opens with a height transition. Transitions to height: auto weren’t possible until recently. interpolate-size: allow-keywords CSF on the root element enables transitions to and from auto, and the ::details-content CSF pseudo-element selects the part of the element that expands.

Will this work in my browser?

Mostly, yes. The newest features here, like if(), @function, display: grid-lanes, interestfor and the carousel’s scroll buttons, mostly only work in Chrome. But, each one sits behind an @supports test or a fallback line, so browsers that don’t support it get a plainer version that still works. This is fine. You can check Can I use for the latest support.

Further reading
  1. MDN’s CSS reference, documentation for every CSS property and feature.
  2. Learn CSS on web.dev, a free course from the basics up.
  3. The Interop dashboard, which tracks cross-browser support for new features.
Where the photos come from

The photos were taken and logged by jsingleton20 (that’s me) on iNaturalist in New Jersey, New York, Massachusetts and beyond. The ASCII mushrooms are drawn after a few of them, and the numbers in the chart, table and counter come from the same records.

accordion.html HTML
<details name="notes" open>
  <summary>Will this work in my browser?</summary>
  …
</details>
<details name="notes">
  <summary>Further reading</summary>
  …
</details>
details.css CSS
:root {
  interpolate-size: allow-keywords;
}

.accordion details::details-content {
  block-size: 0;
  overflow: clip;
  transition:
    block-size 0.5s var(--ease),
    content-visibility 0.5s allow-discrete;
}

.accordion details[open]::details-content {
  block-size: auto;
}
content-visibility needs allow-discrete too, or the content would disappear before the close finished.

Chapter 5 Type and color §

The drop cap at the start of this paragraph uses initial-letter: 3 CSF, which sizes the letter to span three lines and aligns it to them. (Browsers without support still need a float, sadly).

Headings use text-box: trim-both cap alphabetic CSF to remove the space above capital letters and below the baseline. They also use text-wrap: balance CSF to even out line lengths and prevent the unforgivable sin of disharmonious type. Paragraphs use text-wrap: pretty CSF to avoid a single word on the last line, which is a universally agreed upon styling faux-pas.

On wide screens, notes like this one are placed in the rail with anchor positioning, level with their reference number. On narrow screens they appear below the paragraph.

hanging-punctuation CSF moves opening quotation marks outside the text edge (currently Safari only). Vertical spacing uses lh and rlh CSF, which are CSS units equal to one line height, and gives off the supremely elegant result of spacing between blocks which follows the line spacing of the text.

Fluid type§

To achieve the effect where font sizes scale fluidly with the page viewport size, we define a custom CSS function, --fluid(), which takes a minimum and maximum size and returns a clamp() between them. Custom functions (@function CSF) are somewhat new, so for each use, make sure to precede it with a plain ol’ clamp() declaration. Browsers that don’t support @function drop the second declaration and use the first.

base.css CSS
/* vi is 1% of the viewport's inline size: its width, in a left-to-right or right-to-left language */
@function --fluid(--min <number>, --max <number>) returns <length> {
  result: clamp(
    calc(var(--min) * 1rem),
    calc(
      (var(--min) - (var(--max) - var(--min)) * 0.4) * 1rem +
        (var(--max) - var(--min)) * 1.6vi
    ),
    calc(var(--max) * 1rem)
  );
}

body {
  /* never below 1.0625rem or above 1.25rem; in between, it grows by 0.3% of the window width */
  font-size: clamp(1.0625rem, 0.9875rem + 0.3vi, 1.25rem);
  font-size: --fluid(1.0625, 1.25);
}
Line 15 is the fallback and line 16 uses the function. The size reaches its minimum at a 400px viewport and its maximum at 1400px.

vi and cqi§

CSS has a lot of length units available now, and here are two handy ones: vi is 1% of the viewport’s inline size, which is its width in a left-to-right or right-to-left language. It’s the logical version of vw, where if you switch to a vertical writing mode, it follows the text direction, so you don’t need to even think about it. The fluid sizes above all grow in vi.

cqi CSF is the same idea, but it gets measured against the nearest parent container with container-type: inline-size. The gist is that the size adjusts to the containing box instead of the window. For example, the pull quote below is sized in cqi, so if it lands in a narrow column, its text shrinks to fit even on a wide screen. The ASCII mushrooms use 100cqi to make their widest line fill the box exactly.

Earth is cool. Fire’s warm. Root is down. Below the storm. Good time coming. Beat is slow. Inhibition. Let it grow.

Bruce Haack

Pull quote Styled with @scope CSF, and sized in cqi CSF units relative to the quote’s own width
quote.css CSS
.pullquote {
  container-type: inline-size;
}

.pullquote p {
  /* 5.5% of the quote's width, kept between 1.5rem and 2.25rem */
  font-size: clamp(1.5rem, 5.5cqi, 2.25rem);
}
I use vi for page-level type, like body text and headings, and cqi for components that could end up anywhere.

Color§

The Aa menu near the top of the page switches between light, dark and sepia themes. The stylesheet itself has no separate set of dark-mode colors, which is duplicated work I have long been guilty of doing. For this page, every color on the page is derived from two simple values, --paper and --ink.

Both are defined with light-dark() CSF, which takes a light-mode color and a dark-mode color and uses whichever matches the current color-scheme. Colors are written in OKLCH CSF (lightness, chroma, hue). Equal steps in OKLCH lightness look like equal steps to the eye, which isn’t true of hex or RGB values. At least, that’s something I learned recently, but I still have to convert the colors from hex or RGB, because OKLCH is a bit obtuse to look at (for me).

base.css CSS
:root {
  color-scheme: light dark;

  /* The two base colors */
  --paper: light-dark(oklch(97% 0 0), oklch(20.5% 0 0));
  --ink: light-dark(oklch(37.1% 0 0), oklch(92.2% 0 0));

  /* Everything else is derived from them */
  --muted: color-mix(in oklch, var(--ink) 78%, var(--paper));
  --rule: var(--ink);
  --accent-wash: light-dark(
    oklch(from var(--paper) calc(l - 0.06) c h),
    oklch(from var(--paper) calc(l + 0.08) c h)
  );
}
Changing the two base colors changes the whole palette. See color-mix() CSF and relative colors CSF.

Secondary text uses color-mix() to blend 78% ink into the paper color, and rules are the ink itself. These numbers I picked because they looked pretty good. The pale wash behind a footnote you’ve jumped to uses relative color syntax, oklch(from var(--paper) calc(l - 0.06) c h), which takes the paper color, reads its lightness, chroma and hue, and lowers the lightness by 0.06. The sepia theme simply redefines --paper and --ink, and then the rest of the palette updates on its own.

The theme menu is a standard, workhorse <select>. The root element checks its state with :has() CSF: :root:has(option[value="dark"]:checked) matches when the dark option is selected, and sets color-scheme: dark, which causes every light-dark() value on the page then switches to its dark color. Simple.

In the case of this page, sepia is an additional theme, since light-dark() only has two slots. Instead, the sepia rule replaces --paper and --ink outright with warm colors, and pins color-scheme: light. Everything mixed from the two base colors picks up the new colors, and any leftover light-dark() values, like the footnote wash, take their light side. If we wanted to add a fourth theme, we would just add another similar rule.

The text-size menu works the same way by changing the root font-size. And since all sizes on the page are in rem, everything just scales with it.

The theme settings are at the top of the article, but you can also try them from here. The cool thing is that this button opens the same settings panel as the Aa button at the top, so there is still only one theme menu and nothing to keep in sync. The panel has no fixed position: position-area places it relative to its anchor, and a popover’s anchor is whichever button opened it, so it shows up right next to this one.

base.css CSS
:root:has(select[name="theme"] option[value="dark"]:checked) {
  color-scheme: dark; /* every light-dark() value now uses its dark color */
}

:root:has(select[name="theme"] option[value="sepia"]:checked) {
  color-scheme: light; /* any light-dark() left takes its light side */
  --paper: oklch(92% 0.012 95);
  --ink: oklch(20% 0.01 80);
}

/* The text-size menu works the same way */
:root:has(select[name="size"] option[value="l"]:checked) {
  font-size: 112.5%; /* 1rem becomes 18px, and everything sized in rem grows with it */
}
Both menus are ordinary <select name="theme"> and <select name="size"> elements in the Aa popover.

The menus are styled with appearance: base-select CSF, which allows a native select to be fully styled, including the button, the dropdown (::picker(select)), the arrow (::picker-icon) and the selected-option tick (::checkmark). The select also keeps its built-in keyboard and screen-reader support, with no invervention needed.

With the base-select feature, options aren’t limited to just text, which is quite useful in this case. Here each one holds a color chip, and the box gets reskinned based on whichever one is picked with the same :has() trick as the theme menu.

  1. --paper
  2. --tint
  3. --rule
  4. --muted
  5. --ink
Customizable select Each option holds a two-tone chip, and <selectedcontent> copies the chosen one into the button. Picking one sets --paper and --ink on this box with :has(), and the rest of the palette is worked out from those two.

A few other color features are in use too... The chapter bars in the left margin are white with mix-blend-mode: difference CSF, which makes them dark on a light background and light on a dark one. Tooltip text uses contrast-color() CSF, which returns black or white, whichever contrasts more with the background. @media (prefers-contrast: more) CSF darkens secondary text to the full ink color for readers who have requested higher contrast. ::target-text CSF styles the passage a text-fragment link (#:~:text=…) points to.

Chapter 6 Final thoughts §

To fully maximize the C.L.E.A.N. lifestyle, one must submit to the maxim that “constraint breeds creativity” and embrace the (diminishing) limitations inherent in CSS. This means relinquishing the desire to make every feature work in every browser and instead just providing some sane fallbacks. It means yielding to the browser that which thou might like to control, for the benefit of the greater public. It means simply letting go.

The upside to this approach is that you can wash your hands of some scripting and let the browser do the heavy lifting. You can spend more time with friends, family and good food. You can devote more energy to hunting mushrooms in the woods. This freedom, after all, is the essence of living C.L.E.A.N.E.R.

Until next time,

Your pal James 🦠