Moving Shiki's Inline Styles to Classes Without Breaking Cached HTML: Name Each Class After Its Color Pair
With dual themes, rehype-pretty-code writes a roughly 50-character style attribute on every colored token. Here is how I moved those to classes on my own site (hash-based class names, no attribute at all for the default color, CSS written at build time), and what I found when I re-measured production pages: up to 15% less uncompressed HTML, but only 1.4% less over the wire.
In early November I was trimming the article pages on my own site. I had the raw HTML open in the browser's dev tools, and only inside the code blocks did the lines run absurdly long.
<span style="--shiki-dark:#F47067;--shiki-light:#D73A49">const</span>. Every keyword, every bracket, carried the same shape of style attribute.
My notes from that week say these attributes made up 20–30% of the article HTML, that the same string was also embedded in the page's serialized data (so it effectively counted twice), and that the heaviest article page went from 598KB to 434KB once I fixed it. The fix itself is simple: swap the style attributes for classes. But inside that "simple" there was one trap that only shows up after a deploy.
When I re-measured production pages today, a second surprise turned up as well. I'll walk through both.
The short version
Name classes by a hash of the color pair, not a running counter. A counter gets renumbered whenever articles are added, and the old HTML still sitting in the edge cache stops matching the new CSS.
Tokens that use the theme's default color get no attribute at all. CSS custom properties inherit from parent to child, so setting the default pair once on the code element is enough.
What shrinks is uncompressed bytes. On the pages I measured, the compressed transfer size moved by only 1.4%. Whether the change is worth doing depends on which byte count your pages are actually bound by.
What was going on
As an indie developer I run this site on Next.js, converting each MDX article to HTML before the build and serving it from Cloudflare Workers. Code coloring comes from rehype-pretty-code and shiki, with a dark and a light theme set at the same time.
With dual themes, shiki doesn't write colors directly. It emits two custom properties per token, and the page's CSS picks one based on the active theme.
/* The reader-side rules in globals.css (unchanged to this day) */.article-content [data-rehype-pretty-code-figure] code span { color: var(--shiki-dark); font-weight: var(--shiki-dark-font-weight, normal); font-style: var(--shiki-dark-font-style, normal);}[data-theme="light"] .article-content [data-rehype-pretty-code-figure] code span { color: var(--shiki-light); font-weight: var(--shiki-light-font-weight, normal); font-style: var(--shiki-light-font-style, normal);}
The mechanism is clean. The volume was the problem. style="--shiki-dark:#ADBAC7;--shiki-light:#24292E" is about 50 characters on its own, repeated once per colored token. On code-heavy articles the color declarations outgrew the prose.
Meanwhile, the number of distinct color combinations is tiny. The production CSS currently defines 25 pairs, and any one page uses 8 to 11 of them. I was shipping the same 50 characters hundreds of times.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Before moving syntax-highlight styles into classes, you will be able to tell whether your pages are limited by uncompressed bytes or by transfer size, and decide if the change is worth it
✦By deriving class names from a hash of each color pair, you can prevent the quiet bug where HTML still cached at the edge gets painted with the wrong colors after a deploy
✦You will be able to confirm in under a minute that every class in your HTML is actually defined in your CSS, before and after the swap
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
The obvious approach is to number classes in order of appearance: t1, t2, and so on. Since the CSS is rebuilt each time, everything looks right on the build you just ran.
I dropped that idea because of the edge cache. My article HTML stays at the edge for a while, and redeploying the Worker does not clear it. The CSS file, however, is replaced by the new build's version.
With order-of-appearance numbering, adding a new article or editing code in an old one can reshuffle which number maps to which color. For a window of time, old HTML gets painted by new CSS, in the wrong colors. Nothing looks broken, which is exactly why it would take a while to notice.
If the name is computed from the color pair itself, the same pair always gets the same name in every build. Old HTML and new CSS can mix freely and the colors still line up.
// Part of the pre-build script that turns MDX into HTML (Node.js)import crypto from "crypto";import fs from "fs";import path from "path";// The theme's default foreground (github-dark-dimmed / github-light).// Compared against shiki's uppercase hex as-is. Change this when you change themes.const SHIKI_DEFAULT_STYLE = "--shiki-dark:#ADBAC7;--shiki-light:#24292E";const classByStyle = new Map();const styleByClass = new Map();function classFor(style) { const hit = classByStyle.get(style); if (hit) return hit; const hex = crypto.createHash("md5").update(style).digest("hex"); // Five hex digits are plenty; extend to twelve only on a collision let name = `t${hex.slice(0, 5)}`; if (styleByClass.has(name)) name = `t${hex.slice(0, 12)}`; classByStyle.set(style, name); styleByClass.set(name, style); return name;}// Call on the HTML string that rehype-stringify producedexport function compactShikiStyles(html) { return html.replace(/<span style="(--shiki-[^"]*)">/g, (_m, style) => style === SHIKI_DEFAULT_STYLE ? "<span>" : `<span class="${classFor(style)}">` );}// Call once, after every article has been convertedexport function writeShikiCss(outDir) { const rules = [...styleByClass.entries()] .sort(([a], [b]) => (a < b ? -1 : 1)) // stable order keeps diffs readable .map(([name, style]) => `.${name}{${style}}`); const css = `/* shiki token colors (${rules.length}) */\n` + `.article-content [data-rehype-pretty-code-figure] code{${SHIKI_DEFAULT_STYLE}}\n` + rules.join("\n") + "\n"; fs.mkdirSync(outDir, { recursive: true }); fs.writeFileSync(path.join(outDir, "shiki-tokens.css"), css, "utf-8"); console.log(`✓ shiki token classes: ${rules.length}`);}
I'd normally avoid rewriting HTML with a regex. I allow it here because the input is shiki's own output, and the <span style="--shiki- prefix is fixed. Any hand-written style in an article is left alone unless it happens to start with --shiki-.
Bold or underlined tokens put entries like --shiki-dark-font-weight:bold into the same style string. Because the whole string goes into the hash, a pair with the same color but a different weight correctly becomes its own class.
Design 2: default-colored tokens get no attribute at all
This was the part that felt best once it worked. The most common tokens in code are identifiers and punctuation drawn in the theme's default color. Giving those a class still leaves hundreds of class="t1a2b3" attributes, and the savings stall at about half.
CSS custom properties inherit from parent to child, just like color does. So I set the default pair once on the code element and leave default-colored <span>s bare. That's the second line writeShikiCss writes.
/* Top of src/generated/shiki-tokens.css as written by the build (excerpt) */.article-content [data-rehype-pretty-code-figure] code{--shiki-dark:#ADBAC7;--shiki-light:#24292E}.t2f162{--shiki-dark:#F69D50;--shiki-light:#E36209}/* The reader-side rules stay the same. A <span> with no class inherits --shiki-dark / --shiki-light from its code parent, so the usual color: var(--shiki-dark) picks up the default color unchanged */
I didn't touch a single line of the reader-side CSS. Values that used to arrive through a style attribute now arrive through a class or through inheritance. I think the reason nothing broke is that I kept that one contract intact: the reader keeps reading the same variables.
The default constant must match shiki's uppercase hex character for character. If you switch themes and forget it, nothing breaks, but every default token gets a class and the savings visibly drop. When the class count in the build log suddenly jumps, that constant is the first thing I check.
Design 3: write the CSS at build time, and let a missing file stop the build
The generated shiki-tokens.css is not committed (it's in .gitignore). Its contents are decided by the articles on every build, and nobody edits it by hand.
Instead, the root layout imports it.
// src/app/layout.tsx (excerpt)import "./globals.css";import "../generated/shiki-tokens.css"; // only exists after the HTML conversion step
If someone runs the Next.js build without the conversion step, the file isn't there and the build fails on the spot. I would much rather it fail loudly than ship uncolored code. The conversion lives in prebuild, and the Workers Builds command runs it first as well.
Re-measuring showed the transfer size barely moved
This is what I checked again today. I fetched four production article pages, read the class-to-color mapping from each page's CSS, rebuilt the HTML as it looked before the swap, and compared sizes.
# Rebuild the "before" HTML from a production page and its CSS, then compare raw/gzip/brotli# Usage: python3 measure_shiki.py page.html all.cssimport gzipimport reimport sysimport brotli # pip install brotliDEFAULT = "--shiki-dark:#ADBAC7;--shiki-light:#24292E"def restore(html: str, css: str) -> str: table = dict(re.findall(r"\.(t[0-9a-f]{5,12})\{([^}]*)\}", css)) missing = set() def to_style(m): name = m.group(1) if name not in table: missing.add(name) return m.group(0) return f'<span style="{table[name]}">' html = re.sub(r'<span class="(t[0-9a-f]{5,12})">', to_style, html) # Put the attribute back on bare default-colored spans, inside code only html = re.sub( r"(<code[^>]*data-language[^>]*>)(.*?)(</code>)", lambda m: m.group(1) + m.group(2).replace("<span>", f'<span style="{DEFAULT}">') + m.group(3), html, flags=re.S, ) if missing: print("classes missing from CSS:", sorted(missing)) return htmldef sizes(text: str): raw = text.encode("utf-8") return len(raw), len(gzip.compress(raw, 9)), len(brotli.compress(raw, quality=11))if __name__ == "__main__": page = open(sys.argv[1], encoding="utf-8").read() css = open(sys.argv[2], encoding="utf-8").read() now, before = sizes(page), sizes(restore(page, css)) for label, a, b in zip(("raw", "gzip", "brotli"), now, before): print(f"{label:7} before={b:>8} now={a:>8} saved={b - a:>6} ({(b - a) / b * 100:.1f}%)")
all.css is simply every stylesheet the page links to, concatenated. Here's what came back.
Article page (amount of code)
Uncompressed HTML
Reduction
Sent with brotli
Heavy (about 30 code blocks)
360,268 → 305,998 bytes
15.1%
31,618 → 31,169 bytes (1.4%)
Medium
229,452 → 198,693 bytes
13.4%
not measured
Light
166,810 → 150,448 bytes
9.8%
21,679 → 21,425 bytes (1.2%)
Almost none
160,781 → 155,003 bytes
3.6%
not measured
Uncompressed HTML dropped by about 15% on the code-heavy page. The brotli-compressed bytes that actually travel over the network moved by roughly 450 bytes.
In hindsight that's obvious: the same 50 characters repeated hundreds of times is exactly what compression is best at. The repetitive waste had already been mostly cleaned up by compression.
I also loaded the before and after HTML alternately, 24 times each, in a local browser and compared the median time until layout finished. The difference was a few to a dozen milliseconds, which I couldn't tell apart from run-to-run noise.
So where does the change actually help? Applied to my site, there are three places:
At the time, the article HTML was also embedded in the page's serialized data, so the uncompressed weight effectively doubled (on the page I measured today, the article body appears only once)
The converted HTML is stored as files and placed at the edge, so storage and deployment are counted in uncompressed bytes
Crawl limits are also counted against the uncompressed size
In short, it pays off wherever you're bound by uncompressed weight. If transfer size is all you watch, this isn't an urgent change.
What I check after the swap
Look at ✓ shiki token classes: N in the build log. If it jumps far above the usual number, check the default constant.
Grab one article page from production or a local build and run the script above. If even one "class missing from CSS" appears, the HTML and CSS came from different builds.
Check colors on a free article whose full text is visible. On my site, code behind the paywall is hidden and the color rules don't apply there. My notes from that week say explicitly not to use a premium article's preview for this.
Toggle dark and light once each, to confirm the inherited default color is picked up in both themes.
The second check needs nothing more than curl and the script.
# Fetch an article page plus the CSS it loads, then compare before/afterURL="https://example.com/articles/app-dev/some-article"curl -s "$URL" -o page.html: > all.cssfor c in $(grep -oE '/_next/static/[^"]+\.css' page.html | sort -u); do curl -s "https://example.com$c" >> all.cssdonepython3 measure_shiki.py page.html all.css
How much to hand to the Antigravity agent
An agent will write this kind of rewrite in no time. Asked without context, though, it tends to number classes in order of appearance, and its verification stops at the build in front of it, where the cache mismatch is invisible.
When I hand this to an agent, I give it three conditions up front:
Class names must be derived from the color pair, and I include the reason: old HTML lingers at the edge
Report before/after sizes in three forms: raw, gzip, and brotli
Put the "every class in the HTML exists in the CSS" check in the same diff as the change
The agent does the rewriting; I decide which byte count we're trying to shrink. Misreading the numbers is how you end up spending a weekend on an optimization that doesn't pay.
Where people tend to trip
Theme updates change the default color: after upgrading shiki or the theme package, revisit the default constant and the class count in the build log.
CSS minification lowercases hex: the served CSS had #adbac7, not #ADBAC7. The comparison runs on HTML during the build, so it doesn't matter there, but if you cross-check against production CSS, make the comparison case-insensitive.
Hash collisions: names extend to twelve digits only when five collide. It hasn't happened with the 25 pairs in production.
Hand-written styles in articles: any line where you typed a value starting with --shiki- yourself will be swapped too. I had none, but a quick grep before the swap is cheap peace of mind.
Where I draw the line
Moving code-highlight styles into classes makes HTML 10–15% lighter without changing a single pixel. But that lightness is in uncompressed bytes; what travels over the network barely changes.
When Japanese web fonts delayed first paint (the record of removing them to check FCP), the win was in the network itself. This time it's the opposite: no help on the wire, real help for storage and parsing. In both cases the answer sat somewhere other than where I'd guessed before measuring.
If you try one thing, take your most code-heavy article page and put its raw and brotli sizes side by side. The gap between those two numbers is a good gauge of whether this change is worth your time.
Share
Thank You for Reading
Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.