skip to the content

Dev

Olive CSS: Tailwind’s class names, a Lisp engine, no JavaScript

· 30 minutes

Olive CSS generates a utility-class stylesheet from a Guile program. You write the class names you already know from Tailwind, and one plain CSS file comes out.

I wrote it because I was tired of installing a JavaScript toolchain to produce a file whose entire job is to contain CSS. The generator is a Guile library, so a build is a function call with the colours, breakpoints and variants you want, and everything between the palette and the stylesheet is code I can read.

Tailwind’s syntax, a Lisp engine, Vanilla CSS and a utility class stylesheet you own.

The source is at https://github.com/jjba23/olive-css under the MIT licence, the API reference is at https://jointhefreeworld.org/api-docs/olive-css/index.html, and the guide lives in the repository’s docs/ directory.

I’ve spent most of this year on it, and it now builds the stylesheets for everything I run. In September it was a README, a script that wrote a stylesheet and a second script that pruned it. The class names haven’t changed since. What changed is how much of the pipeline became something a project could call, extend and complain about.

The Olive CSS logo: an olive branch between two curly braces


What it looks like #

Nothing new in the markup, if you’ve used Tailwind:

<div class="group m-2 px-4 py-6 bg-jeans-blue-500
            md:bg-asparagus-300 hover:bg-tawny-700">
  <span class="text-white font-bold font-serif group-hover:text-tawny-700">
    Hello Olive CSS!
  </span>
</div>

Five of those classes become these rules, copied out of a build this repo ships:

.px-4{padding-inline:1.12rem;}
.bg-jeans-blue-500{background:oklch(0.452 0.0712 256.28/1);}
.hover\:bg-tawny-700:hover{background:oklch(0.5683 0.1557 45.26/1);}
.group:hover .group-hover\:text-tawny-700{color:oklch(0.5683 0.1557 45.26/1);}
/* and, inside @media (width >= 48rem) { ... } */
.md\:bg-asparagus-300{background:oklch(0.6512 0.0882 137.17/1);}

A class name gets escaped the way CSS escapes a name. A colour is an oklch() triple, so the shades of a palette stay perceptually even instead of drifting the way hand-picked hex values do. Breakpoints are media queries with range syntax, hover rules are flat, and the dark theme is one :where([data-theme=dark], [data-theme=dark] *) scope with every dark: rule inside it. No @supports detection, no custom property for every declaration, no polyfill.

None of that is exotic CSS. It’s just that a generator has to get it right for every family in the framework, and it’s a good sign when what it printed is what you’d have written by hand.

Two programs, one stylesheet #

The generator has no idea which classes your site uses, and it isn’t going to parse your templates to find out. It writes everything: every family, every shade, every state, every breakpoint, the container variants, the dark layer. The palette, the variants and the breakpoints are parameters, so a build is one deterministic function of them. That’s why the full stylesheet is several megabytes. Selector-shaped variants, container queries, composed filters and shadows all come out as whole layers, and each layer costs bytes.

The second program is what makes the first one affordable, because nobody downloads the full sheet.

A site’s build runs the pruner over its own output. The pruner imports one module, (olive-css license), for the header it writes, so it never drags in the generator or any of the declaration modules. It does five things:

  1. Walks the directory and reads class names out of whatever the chosen mode understands: class attributes in HTML, (@ (class "...")) in SXML, className={...} in JSX, :class in Vue, class:name in Svelte, hiccup vectors, Elm calls, literal classes in a PHP, Jinja or HEEx template, and a few more.
  2. Escapes each name the way CSS escapes it (hover:bg-x becomes hover\:bg-x, @sm:flex becomes \@sm\:flex) and drops the duplicates.
  3. Parses the stylesheet into nested blocks instead of matching lines, so a rule inside @media, @container, @supports, @layer or the dark scope is nested rather than a line that happens to contain a dot.
  4. Keeps a rule when a selector in it reaches a used class, keeps the rules with no class at all (the reset, @keyframes), and drops a grouping block that ends up empty.
  5. Writes the result minified, with the same licence header.

On my machine the whole 9 MB build takes about a second to prune:

$ olive-css tree-shake
Tree-shaking (html mode): 89 classes kept
  resources/css/olive.min.css: 9065114 bytes
  public/olive.min.css: 7153 bytes

Two things about that are worth more than the byte count.

A variant can put two class names in one selector, like .group:hover .group-hover\:flex, and only the utility class is matched. So a page that uses group somewhere doesn’t drag every group-hover rule along with it.

And a class the pruner can’t enumerate is a class it can’t keep. That’s the real reason there are no arbitrary values in this framework: w-[13px] has no finite list to generate, so it would be the one class the pruner couldn’t answer for. I’d rather not ship the exception, and it’s the first item under What it doesn’t do.

When the class name is built at run time #

A template that assembles a name from data, (string-append "text-" colour "-500"), can’t be scanned, because the name isn’t in any file. Two parameters cover that, and they compose: preserved-classes keeps names as written, preserved-patterns keeps a family by regular expression.

(use-modules (olive-css tree-shaking))

(parameterize ((artifact-path "_site")
               (scan-mode 'manifest)
               (preserved-classes '("bg-onyx-900" "text-floral-white-100"))
               (preserved-patterns '("text-.*-500")))
  (tree-shake))

What it saves #

Six sites, each one’s whole source tree scanned, and the stylesheet this repo generates for it pruned:

Application Classes Stylesheet Pruned
wikimusic 503 3.80 MB 16.1 KB
lucidplan 358 3.80 MB 14.5 KB
byggsteg 254 3.87 MB 12.8 KB
torikomi 144 3.97 MB 7.5 KB
carvoeiro-water-fun 239 4.49 MB 6.7 KB
iter-vitae 201 3.80 MB 6.6 KB

The scan includes each project’s tests and documentation, so those are upper bounds. They count names rather than rules, and the prune keeps every rule a name reaches: a shade, its opacity modifiers, its states, its variants. The method behind the table, and how to reproduce it, is in the tree-shaking guide.

Bar chart of the pruned stylesheet size for six sites, from 6.6 KB to 16.1 KB
What a browser downloads, after pruning. The same stylesheets as generated are 3.80 to 4.49 MB, so the largest bar here is about 230 times smaller than the input it came from.

WikiMusic, and the afternoon the pruner cost me #

WikiMusic is a free music knowledge encyclopaedia: songs, artists and genres, with guitar and bass tabs, chords, lyrics, keys, tunings and sheet music, written by musicians for anyone learning to play. It’s a Guile application on GNU Artanis, and its views build markup with mk-class:

(class ,(mk-class '(h-16 w-auto)))

That shape is the reason the scheme scan mode exists. It reads every quoted list inside a call to mk-class, follows the call into its own cond and append branches, and reads SXML attributes too. Point it at the sources and the prune needs no rendering and no browser.

Then it got interesting. WikiMusic hands classes to more than one helper: a framework component takes them as #:extra-classes '(...), and one of its own helpers takes a quasiquoted list built around a variable. The mk-class reader saw none of those, so the prune dropped their rules. The site still rendered a page. It rendered one with no gutter in the footer, no ink on a link and no colour behind the page, and it took me an embarrassing afternoon to notice.

The fix is the extension point I’m most pleased with. scan-extractors takes procedures, each one from a file’s text to class names, and runs them next to the mode’s own readers. WikiMusic’s reader takes every quoted list in a file, using Guile’s read instead of a regular expression:

;; shortened: `quoted-classes' and `datum-classes' recurse into the datum.
(define (quoted-class-lists text)
  "The class names every quoted list in TEXT names."
  (let loop ((port (open-input-string text))
             (found '()))
    (catch #t
           (lambda ()
             (let ((form (read port)))
               (if (eof-object? form)
                   found
                   (loop port (append (quoted-classes form) found)))))
           ;; A file the reader cannot finish -- the scripts under `pub/js' are
           ;; not Scheme -- keeps what was read of it: a name kept by mistake
           ;; costs a few bytes, a name missed paints nothing.
           (lambda (key . args) found))))

A reader rather than a pattern, because a class list nests in the row it belongs to ('(500 warning (text-redwood-700 dark:text-redwood-300))), and because only a reader tells a word inside a string or a comment apart from a class. A file that won’t read to the end, like the JavaScript under pub/js, keeps whatever was read of it: a name kept by mistake costs a few bytes, and a name missed costs a colour.

The scan also covers the framework modules the views build markup with, hygguile and kracht and orgwebalchemy, because a component names classes of its own (sr-only, animate-spin, hidden, the ink a button takes on hover) that no view names again.

The pruner also checks #

Reading every quoted list makes the report noisy, since a quoted list also holds a status code, a locale or a route path. So WikiMusic builds its report from a narrower reading, the names a view hands to mk-class or writes in a class attribute, and asks two questions of them.

undefined-classes
every name no stylesheet defines. Most turn out to be hooks a script reads, icon names, or the framework’s own inline sheet. The count gets printed.
unsupported-steps
names that ask for an opacity step the generator doesn’t produce. Only a handful of steps exist, and a class like bg-redwood-500/15 paints nothing at all: no rule, no error, a page quietly missing a tint.

The second one fails the build and names the class. It’s about forty lines, and it’s the olive-css check command the roadmap still lists as not built. That’s the argument for making the pruner a library instead of a tool: a project can ask its own questions about its own output without waiting for me to invent a verb for them.

What WikiMusic serves #

The generated stylesheet is 3.8 MB. The pruned file the instance serves is 23 KB, checked in, because it’s what the site links. It sits beside 76 KB of the project’s own CSS, and the two together are what a page waits for.

The gap between 16.1 KB in the table and the 23 KB it really serves is the reader. WikiMusic reads every quoted list, so it keeps rules for classes its components name and no view repeats. Reading more names keeps more rules, which is the direction I want the error to go in.

WikiMusic's genre list: a responsive grid of illustrated tiles, each naming a genre
The genre list at wikimusic.jointhefreeworld.org. The tiles, the hairlines, the pink button and the grid that reflows on a narrow screen are utility classes in the views; the project's own stylesheet paints the palette and the type over them.
The top of a WikiMusic song page in dark mode: title, key and tuning chips, artwork, and the metronome controls
The same stylesheet with data-theme="dark" set: the dark layer, not a second build. Chord diagrams, selects and the rest of the controls are drawn with the same utilities.

Why a Lisp #

Every framework claims to be configurable. The question is what the configuration is made of. In Olive CSS a knob is a Guile parameter, and a build is a parameterize around one function:

(use-modules (olive-css main)
             (olive-css decl colors))

(define my-project-palettes
  (list (cons 'onyx (onyx))
        (cons 'floral-white (floral-white))))

(parameterize ((with-dark-mode? #f)
               (minified? #t)
               (state-variants '(hover focus))
               (responsive reduced-responsive)
               (responsive-classes (core-utility-classes))
               (palettes my-project-palettes))
  (write-css-to-file #:file "my-build.css"
                     #:css-lines (olive-css-gen)))

Run that with guile -L src my-build.scm and you have a stylesheet. There’s no config file to learn and no plugin protocol, because the thing you’re configuring is already a program. The whole surface fits on one table in docs/customization.org.

A colour is three numbers. make-palette takes an oklch triple, derives the five shades, and every family that mentions a colour picks the new one up:

(use-modules (olive-css dsl)
             (olive-css main))

(define my-colour (make-palette '(0.62 0.15 250)))

(parameterize ((palettes (append (palettes) (list (cons 'my-colour my-colour)))))
  (write-css-to-file #:file "my-build.css"
                     #:css-lines (olive-css-gen)))

After that, bg-my-colour-500 exists, and text-my-colour-300/50, and the ring, outline, accent, caret, fill and stroke forms, because those families read the palette instead of repeating it.

That shape has done more work than I expected:

  • The tree-shaker’s readers are data plus procedures. A mode names a shape, and a build with a shape no mode knows passes a procedure. The extension WikiMusic needed wasn’t a patch to a framework, it was a function in its own build script.
  • The CLI is importable and returns a status instead of exiting. The tests drive the same entry point a build script does: (run-cli '("generate" "--build" "lucidplan")) answers 0.
  • The scales are values, not prose. sizes.scm holds the t-shirt steps, numeric steps, fractions, trackings and alphas, and every family reads that list instead of restating its steps, so changing a multiplier changes the framework coherently.

The cost is honest: to change a family you have to be willing to read Scheme. If all you want is class names, that cost buys you nothing and the defaults are for you. The source is for the day the defaults aren’t enough, and it’s why the answer to “can it do what my design needs” is usually a small diff in one module rather than a fork.

Compared to Tailwind #

Tailwind is a serious piece of software, and a framework that borrows its vocabulary owes it a straight comparison.

  Tailwind CSS Olive CSS
What you install a JavaScript package, or its standalone CLI a Guile library and its command
How classes are found the tool parses your source files the pruner reads built output, or the sources, or a list you declare
Arbitrary values yes: w-[13px], content-['x'], [&>svg] no
Configuration a CSS-first file, with a JavaScript hatch parameterize around a function
Reproducible build the Node toolchain Guix, bit for bit
Licence MIT, with a paid UI kit beside it MIT throughout

They aren’t competing on the same axis. Tailwind’s generator reads your source files and produces classes on demand, but it ships as a JavaScript package (with a native CLI beside it), so adopting it means adopting a toolchain and a version to keep in step with everything else in your front end. Olive CSS generates everything once and prunes the output, which is why it can read HTML, SXML, JSX, hiccup, Elm, PHP or a declared list in the same pass, and why no part of your build has to be JavaScript.

On parity I’d rather be precise than generous: by the project’s own count, an unweighted average over the core utility families, most of Tailwind v4’s surface is covered, and the weak spots are written down in docs/comparison.org instead of being rounded up. SVG is the thinnest family. Arbitrary values are missing entirely.

So pick Tailwind if its ecosystem is the point, if arbitrary values are load-bearing in your design, or if you want a component kit with a support contract. Pick Olive CSS if you want a stylesheet you can read end to end, a build that’s a program you own, and a served file measured in kilobytes instead of in a build log.

Native CSS is enough now #

The output is plain CSS because plain CSS caught up: oklch() for colour, container queries for components that respond to their box instead of the viewport, :has() and :where() for selectors that used to need a class in the markup, range syntax in media queries. What the browser was missing wasn’t a feature. It was a vocabulary: a scale of names a designer, a template and a stylesheet can agree on, plus a way to keep only the part a site uses.

A site that uses Olive CSS has a make target that regenerates one file, and that’s the whole build. No watcher to restart, no plugin to re-audit, no bundler integration to repair after a major version. That’s the part that ages well.

Learning it, and hacking it #

If you know Tailwind, you already know the class names, the variants and the order of md:group-hover:. What you have to learn fits on a page, and it’s all differences: max-w-sm names a container width instead of a spacing step, arbitrary values are absent, a stacked variant is one entry in stacked-variants instead of a free combination, and the colours are this project’s own (onyx, jeans-blue, asparagus, tawny), to use or replace.

For the generator, the entry point is small. A utility family is one module under src/olive-css/decl/, its tests go in one file, and the vocabulary it draws from is a list in sizes.scm. Adding a family means writing the rules you want and letting the existing scales, palettes and variants apply to them. That’s how it grew from a handful of areas to nineteen in a year without turning into a pile of special cases.

The second kind of hacking is the one I didn’t plan for: changing what the pruner knows. scan-extractors and class-call-names came out of projects asking for them, because a reader is just a procedure from a file’s text to class names. If your markup has a shape the shipped modes don’t cover, you don’t open an issue and wait for me. You write a few lines and pass them:

(define (marked-classes text)
  "The classes TEXT names after a `data-classes:' marker."
  (let ((at (string-contains text "data-classes:")))
    (if at
        (map escape-class-name
             (string-tokenize (substring text (+ at 13))))
        '())))

(parameterize ((artifact-path "src")
               (scanned-file-types '(".tpl" ".conf"))
               (scan-extractors (list marked-classes)))
  (tree-shake))

What it doesn’t do #

The repo keeps a list of what it can’t do, and it’s worth reading before you decide anything:

  • Arbitrary values. w-[13px], content-['x'], [&>svg]. A static generator can’t enumerate them, and a class it can’t enumerate is a class the pruner can’t keep. There’s a design for one small, recognised shape. It isn’t built.
  • Stacked variants by default. md:group-hover: exists, one entry per combination in stacked-variants, because each combination costs its product in bytes. The machinery is there. The cross-product is a budget question.
  • Mask colour stops and stroke-dasharray. Two small gaps in families Tailwind has.
  • Cascade layers. The pruner understands @layer blocks, the generator doesn’t emit them yet, so a site’s own CSS still needs the usual specificity care.
  • olive-css check and olive-css size. The pruner already scans and already knows every selector it kept, so both are reporting modes rather than new machinery. WikiMusic wrote the first one in its own build script. The second would put a byte count on every release.

None of that is a promise with a date.

Try it #

From a checkout:

guix time-machine --channels=channels.scm -- shell -m manifest.scm -- maak build
./bin/olive-css generate --build full --output app.css
./bin/olive-css tree-shake --directory public --output app.min.css

There are install routes for Guix, Nix, a container, and Debian, openSUSE and Arch recipes under packaging/; the Guix one needs the guix-jointhefreeworld channel checked out beside the project. The four install routes and a first page are in docs/getting-started.org.

If you find a class that paints nothing, a name the pruner misses, or a family you’d rather have written yourself, that’s the kind of report this project is built to act on. The backlog is at https://lucidplan.jointhefreeworld.org/tickets/olive-css.

Closing #

A stylesheet is one of the few things on a web page you can still read all the way down: rules, selectors, values. Having a generator in front of it isn’t a problem. Having a black box in front of it is. This year’s work was making that box less opaque: a build I can call from a Scheme prompt, a pruner that tells me which classes it kept and which names nothing defines, and a served file I can account for line by line.

So it isn’t that Lisp makes CSS faster, and it isn’t that a framework should be a language. It’s that a framework you can rewrite is a better neighbour to a browser than one you can only configure.

If you’ve been meaning to drop the toolchain from a project and haven’t found the excuse yet, try it and tell me what broke.