Build guide · CSS and web
Liquid glass in CSS, with real refraction
Blur with a white border is glassmorphism. Liquid glass bends the backdrop at its edge, and on the web that takes an SVG displacement map applied through backdrop-filter: url(). Chromium browsers render it; Safari and Firefox fall back to frost, so ship both.
More about CSS and web
Below is the whole web recipe the Meniscus MCP server hands to coding agents: the displacement map in framework-free TypeScript, the markup and CSS, a React component, the rules that make or break it, the frost fallback and a WebGL shader for hero visuals.
Updated · the recipe the Meniscus MCP server returns for this medium
In short: Tier A — an SVG displacement map applied through backdrop-filter: url() — with the CSS frost fallback; the WebGL shader for hero and effect visuals.
Limits: the tier A bend renders only in Chromium browsers; Safari and Firefox get tier B frost with no bend, so screenshot both. The WebGL tier bends only a backdrop it can sample (an image, video or drawn scene), not the live DOM.
Tiers
| Tier | Where | What you get |
|---|---|---|
| A. SVG displacement backdrop | Chromium browsers (Chrome, Edge, Arc, Opera, Brave; also headless Chrome for screenshots) | real bezel refraction of the live page |
| B. CSS frost fallback | Safari, Firefox, and when A is disabled | blur + saturation + fill + rim; no bending |
| C. WebGL / canvas shader | all browsers, when the backdrop is known (an image, video or a scene you draw) | refraction, dispersion, frost noise, caustics, iridescence, morph |
Ship A with B as the automatic fallback for UI chrome. Use C for hero visuals and effect panels. Never ship B alone and call it liquid glass.
A1. Displacement map (framework-free TypeScript)
export type Profile = "bevel" | "convex" | "rim" | "flat";
// Backdrop shift across the bezel, s = 0 at the outer edge .. 1 at its inner end, edge = 1. Paraxial refraction
// (IOR 1.5) through a rounded edge follows the surface slope; a finite slope at the silhouette spreads the bend over the
// whole bezel. bevel: edge 1 − (1 − s)³ → shift (1 − s)². convex: a dome over a circle (bezel = radius), the whole
// face magnifies. rim: the bevel in the outer 35 % only.
const BEND: Record<Profile, (s: number) => number> = {
bevel: (s) => (1 - s) ** 2,
convex: (s) => ((1 - s) * (2 - s)) / 2,
rim: (s) => (s < 0.35 ? (1 - s / 0.35) ** 2 : 0),
flat: () => 0,
};
// Fold limit: displacement × steepest slope must stay under the bezel (bevel 0.5 × bezel, convex 0.67, rim 0.17).
const SLOPE: Record<Profile, number> = { bevel: 2, convex: 1.5, rim: 2 / 0.35, flat: 0 };
export const maxDisplacement = (bezel: number, profile: Profile) => (SLOPE[profile] ? bezel / SLOPE[profile] : 0);
// Corner shape: "round" is CSS border-radius; "squircle" is CSS `corner-shape: squircle`, a superellipse with exponent 4
// inside the same corner box (measured in Chrome: on a 200 px square the edge sits 119 px out along the diagonal,
// where a circle reaches 100). The map and the element must use the same one, so the bend follows the visible edge.
export type Corner = "round" | "squircle";
export const squircleCorners = typeof CSS !== "undefined" && CSS.supports?.("corner-shape", "squircle") === true;
function sdShape(x: number, y: number, w: number, h: number, r: number, corner: Corner) {
const qx = Math.abs(x - w / 2) - (w / 2 - r), qy = Math.abs(y - h / 2) - (h / 2 - r);
if (corner === "squircle" && r > 0 && qx > 0 && qy > 0) return r * (((qx / r) ** 4 + (qy / r) ** 4) ** 0.25 - 1);
return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;
}
const maps = new Map<string, string>();
export function displacementMap(w: number, h: number, radius: number, bezel: number, profile: Profile, corner: Corner = "round"): string {
const key = `${w}x${h}:${radius}:${bezel}:${profile}:${corner}`;
const hit = maps.get(key);
if (hit) return hit;
const canvas = document.createElement("canvas");
canvas.width = w; canvas.height = h;
const ctx = canvas.getContext("2d")!, img = ctx.createImageData(w, h), d = img.data;
const bend = BEND[profile], r = Math.min(radius, w / 2, h / 2);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
const px = x + 0.5, py = y + 0.5, depth = -sdShape(px, py, w, h, r, corner);
let dx = 0, dy = 0;
if (depth > 0 && depth < bezel) {
const nx = sdShape(px + 0.5, py, w, h, r, corner) - sdShape(px - 0.5, py, w, h, r, corner);
const ny = sdShape(px, py + 0.5, w, h, r, corner) - sdShape(px, py - 0.5, w, h, r, corner);
const len = Math.hypot(nx, ny) || 1, m = bend(depth / bezel);
dx = (-nx / len) * m; dy = (-ny / len) * m; // inward: the rim shows backdrop from further inside
}
const i = (y * w + x) * 4;
d[i] = 128 + dx * 127; d[i + 1] = 128 + dy * 127; d[i + 2] = 128; d[i + 3] = 255;
}
ctx.putImageData(img, 0, 0);
const url = canvas.toDataURL();
maps.set(key, url);
return url;
}
// SVG filter markup for one element size. displacement = max shift in px at the outer edge.
// Mount it inside an <svg><defs> (defs.insertAdjacentHTML("beforeend", markup)) so it parses as SVG; see A4 rule 2b.
// The bezel is capped at the corner radius (deeper, the corner creases on its diagonal) and the displacement at the
// profile's fold limit.
export function glassFilterSvg(id: string, o: { w: number; h: number; radius: number; bezel: number;
profile: Profile; displacement: number; blur: number; saturate?: number; corner?: Corner }): string {
const bezel = Math.min(o.bezel, o.radius, o.w / 2, o.h / 2);
const displacement = Math.min(o.displacement, maxDisplacement(bezel, o.profile));
const map = displacementMap(o.w, o.h, o.radius, bezel, o.profile, o.corner ?? "round");
return `<filter id="${id}" x="0" y="0" width="${o.w}" height="${o.h}" filterUnits="userSpaceOnUse"
color-interpolation-filters="sRGB">
<feImage href="${map}" x="0" y="0" width="${o.w}" height="${o.h}" preserveAspectRatio="none" result="map"/>
<feDisplacementMap in="SourceGraphic" in2="map" scale="${displacement * 2}"
xChannelSelector="R" yChannelSelector="G" result="bent"/>
<feGaussianBlur in="bent" stdDeviation="${Math.max(o.blur, o.profile === "convex" ? 1 : 0.5)}" result="frost"/>
<feColorMatrix in="frost" type="saturate" values="${o.saturate ?? 1.4}"/>
</filter>`;
}
// Chromium is the only engine that renders SVG filters inside backdrop-filter. Keep the userAgentData test: headless
// Chrome reports "HeadlessChrome/…", which the regex alone misses, so screenshot QA would only see the fallback.
export const supportsSvgBackdrop = typeof navigator !== "undefined" &&
("userAgentData" in navigator || /\bChrome\/\d+/.test(navigator.userAgent)) &&
!/Firefox|FxiOS|CriOS|EdgiOS/.test(navigator.userAgent);A2. Markup and CSS
One glass body = a positioned element with four children: the optic layer (backdrop filter + fill), the glow, the rim, and the content. Keeping the optics on a child keeps content out of the filter. The children are <span>s, so the same markup is valid inside a <button> host.
<div class="glass" style="--radius:22px">
<span class="glass__optic"></span> <!-- --glass-filter: url(#id) in Chromium, blur() elsewhere -->
<span class="glass__glow"></span>
<span class="glass__rim"></span>
<span class="glass__content">Button</span>
</div>:root {
--glass-fill: rgba(255,255,255,.15); /* regular */
--glass-fill-lens: rgba(255,255,255,.06);
--glass-fill-frost: rgba(255,255,255,.28);
--glass-fill-pill: rgba(255,255,255,.28); /* a tab bar's or segmented control's selected pill */
--glass-rim-key: rgba(255,255,255,.96);
--glass-rim-side: rgba(255,255,255,.24);
--glass-rim-counter: rgba(255,255,255,.56);
--glass-edge: rgba(0,0,0,.12);
--glass-edge-contrast: rgba(0,0,0,.2); /* increased contrast */
--glass-glow-key: rgba(255,255,255,.8);
--glass-glow-counter: rgba(255,255,255,.35);
--glass-shadow: 0 8px 28px rgba(0,0,0,.14), 0 1px 3px rgba(0,0,0,.08);
--glass-solid: rgba(245,245,247,.92); /* reduced transparency */
--glass-ink: #1d1d1f;
--glass-accent-ink: #143fa8; /* accent labels and icons on glass */
--scroll-edge-dim: rgba(255,255,255,.55);
}
@media (prefers-color-scheme: dark) {
:root { --glass-fill: rgba(18,18,24,.30); --glass-fill-lens: rgba(18,18,24,.14); --glass-fill-frost: rgba(18,18,24,.40);
--glass-fill-pill: rgba(255,255,255,.12); --glass-rim-key: rgba(255,255,255,.68); --glass-rim-side: rgba(255,255,255,.14);
--glass-rim-counter: rgba(255,255,255,.35); --glass-edge: rgba(0,0,0,.32); --glass-edge-contrast: rgba(255,255,255,.35);
--glass-glow-key: rgba(255,255,255,.5); --glass-glow-counter: rgba(255,255,255,.2); --glass-shadow: 0 10px 32px rgba(0,0,0,.35);
--glass-solid: rgba(36,36,42,.94); --glass-ink: #fff; --glass-accent-ink: #c4d7ff; --scroll-edge-dim: rgba(0,0,0,.55); }
}
/* The edge line is a 1 px ring outside the silhouette, drawn with the shadow so it follows the radius. */
.glass { --fill: var(--glass-fill); --blur-fallback: 14px; position: relative; isolation: isolate; border-radius: var(--radius);
box-shadow: 0 0 0 1px var(--glass-edge), var(--glass-shadow); color: var(--glass-ink);
/* the host must paint nothing: a <button>/<input> host otherwise brings the UA face colour
(grey rgb(107,107,107) under color-scheme: dark) and the optic refracts that instead of the page */
background: transparent; border: 0; -webkit-appearance: none; appearance: none; font: inherit; }
/* One fill per material; set --fill on a body for anything else. */
.glass--lens { --fill: var(--glass-fill-lens); --blur-fallback: 6px; }
/* Glass over a camera, video or photo (on the body or a wrapper): white labels in both themes, a dark solid when
transparency is reduced, and the local dim under it carries the contrast. */
.on-media { --glass-ink: #fff; --glass-accent-ink: #c4d7ff; --glass-solid: rgba(28,28,30,.92); }
.glass--frost { --fill: var(--glass-fill-frost); --blur-fallback: 24px; }
.glass--pill { --fill: var(--glass-fill-pill); --blur-fallback: 6px; box-shadow: 0 0 0 1px var(--glass-edge); }
/* A pill stays a pill at the tinted end: its fill grows at most 1.5×, or the accent label on it loses contrast. */
.glass--pill > .glass__optic { background: rgb(from var(--fill) r g b / calc(alpha * min(var(--glass-amount, 1), 1.5) * var(--materialize, 1))); }
/* Direct children only: a glass body nested in another's content (a tab bar's moving pill) keeps its own position. */
.glass > * { position: absolute; inset: 0; border-radius: inherit; display: block; }
/* --glass-filter is set to url(#id) where the bend works (Chromium); elsewhere the blur below is the frost fallback.
--glass-amount scales every fill: 0.5 and 2 are the clear and tinted ends to check. */
.glass__optic { background: var(--fill);
background: rgb(from var(--fill) r g b / calc(alpha * var(--glass-amount, 1) * var(--materialize, 1)));
-webkit-backdrop-filter: var(--glass-filter, blur(var(--blur-fallback, 12px)) saturate(1.5));
backdrop-filter: var(--glass-filter, blur(var(--blur-fallback, 12px)) saturate(1.5)); }
/* Tier B (no SVG backdrop, set by mountGlass): 4 % more fill, since no bend separates the glass from the backdrop. */
.glass-frost-only .glass__optic { background: rgb(from var(--fill) r g b / calc((alpha * var(--glass-amount, 1) + .04) * var(--materialize, 1))); }
.glass__glow { pointer-events: none;
box-shadow: inset 2px 3px 8px -4px var(--glass-glow-key),
inset -2px -3px 8px -4px var(--glass-glow-counter); }
/* Offset inset highlights follow the silhouette: the lit band is widest where the edge faces the light,
so a wide capsule is lit along its whole top edge (a 135° gradient border would light only its left end). */
.glass__rim { pointer-events: none;
box-shadow: inset 1.5px 1.5px 0 -.5px var(--glass-rim-key),
inset -1.5px -1.5px 0 -.5px var(--glass-rim-counter),
inset 0 0 0 .5px var(--glass-rim-side); }
.glass__content { position: relative; inset: auto; }
/* Press grows the body (mountGlass adds .is-pressed and 15 % more bend); a spring-like overshoot. */
.glass { transition: transform .32s cubic-bezier(.3, 1.45, .5, 1); }
.glass.is-pressed { transform: scale(1.04); }
/* Panels get continuous corners where the browser draws them (rule 5); the map must then use corner "squircle"
(A1 squircleCorners). corner-shape is not inherited, so the layers take it too. Capsules and circles stay round. */
@supports (corner-shape: squircle) {
.glass--squircle, .glass--squircle > * { corner-shape: squircle; }
}
/* :root raises these above the tier B and per-body rules. */
@media (prefers-reduced-transparency: reduce) {
:root .glass > .glass__optic { backdrop-filter: none; -webkit-backdrop-filter: none; background: var(--glass-solid); }
}
@media (prefers-contrast: more) {
:root .glass { box-shadow: 0 0 0 1px var(--glass-edge-contrast), var(--glass-shadow); }
}
@media (prefers-reduced-motion: reduce) {
:root .glass, :root .glass * { transition: none !important; }
}In Chromium set the custom property on the optic, optic.style.setProperty("--glass-filter", "url(#id)") (the filter already contains blur and saturation); mountGlass (M) and the React component (A3) do it. A custom property, not an inline backdropFilter: an inline value would beat the reduced-transparency rule above. A page with one theme only (a dark-only scene): put that theme's values in :root and drop the media query. Fills: .glass is regular; add glass--lens, glass--frost or glass--pill, or set --fill on one body for any other colour (a tint: --fill: rgba(43,107,255,.32)). Never set background on the optic inline: reduced transparency must still win. --glass-amount on :root scales every fill; 0.5 and 2 are the clear and tinted ends to screenshot. Solid states are not glass (a selected chip in the accent, a switch knob white at rest): paint them on the content layer, not through --fill, so --glass-amount leaves them solid. --blur-fallback is the Tier B blur per material: lens 6 px, regular 14 px, frost 24 px, tint 14 px, rim 8 px, flat 0 (no backdrop filter at all).
The Tier A blur is the filter's own (blur in glassFilterSvg, an SVG stdDeviation in px), per material: lens 0.5–1, regular 2–6, frost 10–20, tint 1–4, rim 0.5–2. Use the low end over calm backdrops and the top over busy ones (text, fine photo detail), so what shows through reads as colour and soft shape. On a bar over a fine grid, 2–3 keeps the lines that show the bend.
Corners: give a panel (radius under half its shorter side) class="glass glass--squircle" and build its map with corner: squircleCorners ? "squircle" : "round". Where corner-shape is missing the class does nothing and the map stays round, so the two always match. Capsules and circles keep round.
A3. React component
import { useId, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { glassFilterSvg, squircleCorners, supportsSvgBackdrop, type Profile } from "./liquidGlass";
type GlassProps = { radius: number; bezel: number; displacement: number; blur: number; profile?: Profile;
/** Continuous corners for panels, where the browser draws them; capsules and circles leave it off. */
squircle?: boolean;
fill?: string; className?: string; style?: CSSProperties; children?: ReactNode };
export function Glass({ radius, bezel, displacement, blur, profile = "bevel", squircle = false, fill, className, style, children }: GlassProps) {
const corner = squircle && squircleCorners ? "squircle" : "round";
const ref = useRef<HTMLDivElement>(null);
const id = "lg" + useId().replace(/[^a-zA-Z0-9]/g, "");
const [size, setSize] = useState<{ w: number; h: number } | null>(null);
useLayoutEffect(() => {
const el = ref.current!;
const ro = new ResizeObserver(() => {
const w = Math.round(el.offsetWidth), h = Math.round(el.offsetHeight); // layout size, unaffected by transforms
setSize((s) => (s && s.w === w && s.h === h ? s : { w, h }));
});
ro.observe(el);
return () => ro.disconnect();
}, []);
const svg = supportsSvgBackdrop && size && size.w > 0 && size.h > 0
? glassFilterSvg(id, { w: size.w, h: size.h, radius, bezel: Math.min(bezel, size.w / 2, size.h / 2),
profile, displacement, blur, corner }) : null;
return (
<div ref={ref} className={`glass ${corner === "squircle" ? "glass--squircle " : ""}${className ?? ""}`} style={{ ...style, ["--radius" as string]: radius + "px" }}>
{svg && <svg width="0" height="0" style={{ position: "absolute", width: 0, height: 0, pointerEvents: "none" }} aria-hidden dangerouslySetInnerHTML={{ __html: `<defs>${svg}</defs>` }} />}
<span className="glass__optic" style={{ ...(svg ? { "--glass-filter": `url(#${id})` } : {}), ...(fill ? { "--fill": fill } : {}) } as CSSProperties} />
<span className="glass__glow" />
<span className="glass__rim" />
<span className="glass__content">{children}</span>
</div>
);
}Usage (displacement = 0.4 × bezel for bevel bodies, 0.5 × radius for convex circles, design language §4): button <Glass radius={22} bezel={22} displacement={9} blur={0.8}>Button</Glass>; panel <Glass radius={28} bezel={28} displacement={11} blur={3} squircle>…</Glass>; avatar <Glass radius={32} bezel={32} displacement={16} blur={0} profile="convex" />.
M. Mount without a framework (plain JavaScript)
For a page without React (or any framework: call it once the element exists). Port A1 to liquidGlass.js (drop the types and !), then mount each glass body; an element that already has content gets it wrapped in .glass__content. Expect the bend to show clearly at corners and capsule ends and as a few px along long straight edges; do not raise the numbers to see more.
import { glassFilterSvg, squircleCorners, supportsSvgBackdrop } from "./liquidGlass.js"; // A1, ported to JS
let defs = null, count = 0;
if (!supportsSvgBackdrop) document.documentElement.classList.add("glass-frost-only");
// One hidden <svg><defs> holds every filter on the page. The HTML parser puts <svg> and what is inside it in the
// SVG namespace, so the filters parse as SVG (A4 rule 2b) without naming the namespace.
function filterDefs() {
if (defs) return defs;
document.body.insertAdjacentHTML("beforeend",
'<svg aria-hidden="true" style="position:absolute;width:0;height:0;pointer-events:none"><defs></defs></svg>');
return (defs = document.body.lastElementChild.firstElementChild);
}
/**
* Makes `el` a glass body: wraps its children in `.glass__content` (if they are not already), adds the optic, glow
* and rim layers, and draws a filter for its size (again when the size changes). Pressing grows the bend 15 %:
* `interactive` listens on the body itself; `press(true | false)` drives it from elsewhere (the tabs above a pill).
* Numbers in px: displacement 0.4 × bezel (bevel) or 0.5 × radius (convex circle); blur per material (A2).
*/
export function mountGlass(el, { radius, bezel, displacement, blur, profile = "bevel", squircle = false, interactive = false }) {
if (!el.querySelector(":scope > .glass__content")) {
const content = Object.assign(document.createElement("span"), { className: "glass__content" });
content.append(...el.childNodes);
el.append(content);
}
for (const layer of ["rim", "glow", "optic"]) {
if (!el.querySelector(`:scope > .glass__${layer}`)) el.prepend(Object.assign(document.createElement("span"), { className: `glass__${layer}` }));
}
const corner = squircle && squircleCorners ? "squircle" : "round";
el.classList.add("glass");
el.classList.toggle("glass--squircle", corner === "squircle");
el.style.setProperty("--radius", `${radius}px`);
const optic = el.querySelector(":scope > .glass__optic");
const id = `glass-${++count}`;
let pressed = false, drawn = "";
const draw = () => {
if (!supportsSvgBackdrop) return;
const w = Math.round(el.offsetWidth), h = Math.round(el.offsetHeight); // layout size, unaffected by transforms
const key = `${w}x${h}:${pressed}`;
if (!w || !h || key === drawn) return;
drawn = key;
document.getElementById(id)?.remove();
filterDefs().insertAdjacentHTML("beforeend", glassFilterSvg(id, { w, h, radius, bezel: Math.min(bezel, w / 2, h / 2),
profile, corner, displacement: displacement * (pressed ? 1.15 : 1), blur }));
if (!(document.getElementById(id) instanceof SVGFilterElement)) throw new Error("glass filter did not parse as SVG");
// A custom property, not an inline backdrop-filter, so the reduced-transparency rule still wins.
optic.style.setProperty("--glass-filter", `url(#${id})`);
};
const ro = new ResizeObserver(draw);
ro.observe(el);
const press = (on) => { pressed = on; el.classList.toggle("is-pressed", on); draw(); };
if (interactive) {
el.addEventListener("pointerdown", () => press(true));
for (const type of ["pointerup", "pointerleave", "pointercancel"]) el.addEventListener(type, () => press(false));
}
return { el, press, filter: () => document.getElementById(id), unmount: () => { ro.disconnect(); document.getElementById(id)?.remove(); } };
}T. Tab bar with a pill, a search lens and the scroll edge
A tab bar with its moving pill and a separate search lens, over content that scrolls under it, with the scroll-edge band (design language §8.6), mounted with mountGlass (M; React: one Glass per body, A3). The pill is a glass body inside the bar's content: it keeps its own optics and moves with translate, so its map never changes and the press scale (on transform) still shows; the tabs above it press it. Leave the search lens out when the app has no search or prominent action. Numbers from the tab-bar spec.
<div class="scroll-edge" style="--bar-top: 76px"></div> <!-- bar 60 + 16 from the bottom -->
<nav class="dock">
<div class="tab-bar" role="tablist" aria-label="Sections">
<span class="glass__content">
<span class="tab-bar__pill glass--pill"><span class="glass__content"></span></span>
<button class="tab" role="tab" aria-selected="true"><svg …></svg>Feed</button>
<button class="tab" role="tab" aria-selected="false"><svg …></svg>Explore</button>
<!-- 3–5 tabs -->
</span>
</div>
<button class="search-lens glass--lens" aria-label="Search"><span class="glass__content"><svg …></svg></span></button>
</nav>/* The scroll-edge band behind a floating tab bar (design language §8.6): blur and dim at the bar, fading upward.
--bar-top = the bar's top edge measured from the bottom of the screen. */
.scroll-edge { position: fixed; left: 0; right: 0; bottom: 0; z-index: 1; pointer-events: none;
height: calc(var(--bar-top, 92px) + 16px);
-webkit-backdrop-filter: blur(3px); backdrop-filter: blur(3px);
background: linear-gradient(to top, var(--scroll-edge-dim) 60%, transparent);
-webkit-mask-image: linear-gradient(to top, #000 60%, transparent); mask-image: linear-gradient(to top, #000 60%, transparent); }
.dock { position: fixed; left: 20px; right: 20px; bottom: calc(16px + env(safe-area-inset-bottom)); z-index: 2;
display: flex; gap: 12px; height: 60px; }
.tab-bar { flex: 1; }
.tab-bar > .glass__content { display: grid; grid-template-columns: repeat(4, 1fr); height: 100%; padding: 0 4px; }
.tab-bar__pill { position: absolute; top: 4px; left: 4px; height: 52px; width: calc((100% - 8px) / 4);
transition: translate .38s cubic-bezier(.3, 1.3, .5, 1), transform .32s cubic-bezier(.3, 1.45, .5, 1); }
.tab { all: unset; position: relative; display: grid; place-items: center; align-content: center; gap: 2px;
font-size: 11px; font-weight: 600; cursor: pointer; }
.tab[aria-selected="true"] { color: var(--glass-accent-ink); }
.tab:focus-visible { outline: 2px solid var(--glass-accent-ink); outline-offset: -4px; border-radius: 22px; }
.search-lens { width: 60px; height: 60px; display: grid; place-items: center; cursor: pointer; }
@media (prefers-reduced-motion: reduce) { .tab-bar__pill { transition: none; } }mountGlass(document.querySelector(".tab-bar"), { radius: 30, bezel: 22, displacement: 8.8, blur: 3 });
const pill = document.querySelector(".tab-bar__pill");
const pillGlass = mountGlass(pill, { radius: 26, bezel: 26, displacement: 10.4, blur: 1 });
mountGlass(document.querySelector(".search-lens"), { radius: 30, bezel: 30, displacement: 15, blur: 1, profile: "convex", interactive: true });
const tabs = [...document.querySelectorAll(".tab")];
tabs.forEach((tab, i) => {
// The tabs sit above the pill, so they press it.
tab.addEventListener("pointerdown", () => pillGlass.press(true));
for (const type of ["pointerup", "pointerleave", "pointercancel"]) tab.addEventListener(type, () => pillGlass.press(false));
tab.addEventListener("click", () => {
tabs.forEach((t) => t.setAttribute("aria-selected", String(t === tab)));
pill.style.translate = `${i * 100}% 0`;
});
});A4. Rules that make or break the web version
color-interpolation-filters="sRGB"on the filter. Without it the neutral value 128 is converted to linear light and the whole backdrop slides sideways.filterUnits="userSpaceOnUse",x=0 y=0 width/height= the element's integer px size, the same size onfeImage. Regenerate the map when the size changes (ResizeObserver) and cache maps by size. 2b. Mount the filter as SVG. Insert the markup into an<svg><defs>element (defs.insertAdjacentHTML, or the<svg>'sinnerHTML). Parsed through an HTML<template>, a<div>orDOMParserwithtext/html, it becomes an HTML element namedfilter: Chrome then drops the wholebackdrop-filterwithout an error — no blur, no bend, the glass turns fully clear. Checkdocument.getElementById(id) instanceof SVGFilterElement.- Order displacement → blur → saturate.
feDisplacementMapsamples nearest-neighbour; blurring after it removes the jaggies. Minimum blur 0.5 px, and 1 px on convex lenses: they magnify their whole face (up to 4× at the rim), and below 1 px the magnified backdrop shows 2–3 px stair steps. Blurring before the bend does not remove them. scaleonfeDisplacementMap= 2 × displacement (it shifts byscale × (channel − 0.5)). 4b. Profile and share, not bigger numbers. Use the BEND curves above with displacement 0.4 × bezel (bevel) or 0.5 × radius (convex);glassFilterSvgholds it to the fold limit. An edge that stands vertical at the silhouette (Snell's law through a squircle or quarter-circle surface) packs nearly all of the bend into the outer 1–2 px, so small values show nothing and large ones flip into mirrored rings: the glass reads as blur-only either way. Above an 80 px bezel the 8-bit map quantises; keep those bodies at ≤ 0.4 × bezel or use tier C.- Encode the inward direction:
R = 128 + 127·dx,G = 128 + 127·dy, alpha 255. - Map corner radius = CSS
border-radius, and map corner shape = CSScorner-shape(round, or squircle where the browser draws it);backdrop-filteris clipped to the element's rounded shape. 6b. The glass host paints nothing. Whatever the host element (or any wrapper between it and the page) paints is what the optic refracts.<button>,<input>,<select>hosts get a UA background — a flat grey undercolor-scheme: dark— so the control turns into grey plastic. Resetbackground: transparent; border: 0; appearance: noneon every glass host (the.glassrule above does it) and keep fills on.glass__opticonly. - Backdrop root: an ancestor with
filter,opacity < 1,mask,clip-path,mix-blend-mode,backdrop-filterorwill-changeof those makes nested glass see only that ancestor's content, not the page. This is one more reason children of glass are flat. Animate opacity on the content layer, not on a glass ancestor. - Budget: every visible glass body is one filter pass per frame. Keep ~10–15 bodies on screen at once; a long gallery page can hold more because off-screen bodies are not painted (drop the filter with an IntersectionObserver if a page has 30+). Animate with
transform(not width/height) and quantise animated sizes if you must resize. - Backdrop under every body: nothing opaque between the page backdrop and the glass (no dark demo tiles, no section fills), and no
background-attachment: fixed/ single fixed full-screen image on long pages — give each section its own backdrop that scrolls with it. Otherwise the filter bends a flat colour and the glass looks like grey plastic. - Visual QA: headless Chrome renders these filters, so screenshot tests are valid. Screenshot every section over a grid and over the real backdrop; lines must bend inside each bezel and nowhere be mirrored.
Grid test backdrop (CSS, no asset needed), dark and light: it checks the bend, not text contrast. Judge legibility over the real backdrop.
.grid-backdrop {
background:
linear-gradient(rgba(255,255,255,.55) 1px, transparent 1px) 0 0 / 32px 32px,
linear-gradient(90deg, rgba(255,255,255,.55) 1px, transparent 1px) 0 0 / 32px 32px,
radial-gradient(60% 80% at 20% 20%, #e0435e, transparent 60%),
radial-gradient(60% 80% at 80% 30%, #2b4de0, transparent 60%),
radial-gradient(60% 80% at 60% 100%, #2fb57a, transparent 60%), #10131f;
}
.grid-backdrop--light {
background:
linear-gradient(rgba(20,24,40,.28) 1px, transparent 1px) 0 0 / 32px 32px,
linear-gradient(90deg, rgba(20,24,40,.28) 1px, transparent 1px) 0 0 / 32px 32px,
radial-gradient(60% 80% at 20% 20%, #ffb3c1, transparent 60%),
radial-gradient(60% 80% at 80% 30%, #a9bcff, transparent 60%),
radial-gradient(60% 80% at 60% 100%, #a6e8c8, transparent 60%), #f6f7fb;
}B. CSS frost fallback
The same markup without the SVG: with no --glass-filter, .glass__optic falls back to blur(var(--blur-fallback)) saturate(1.5). mountGlass puts glass-frost-only on <html> there, and the fill rises 4 % because no bend separates the glass from the backdrop (the A2 rule).
C. WebGL fragment shader (known backdrop)
Draw the backdrop texture and the glass in one full-screen pass. Uniforms: uBackdrop texture, uRes canvas px, uRect glass rect (x, y, w, h in px, y down), uRadius, uBezel, uDisp (px), uFrost (0–1), uProfile (0 bevel, 1 convex, 2 rim), uTime. Panels and capsules: uBezel = corner radius, uDisp = 0.4 × uBezel. For a circle lens: uRadius = uBezel = min(w, h) / 2, uProfile = 1, uDisp = 0.5 × radius. Keep uDisp under the fold limit (0.5 × bezel bevel, 0.67 × radius convex, 0.17 × bezel rim); the same values hold over photos, text and grids. For several glass bodies loop over an array of rects (or draw one quad per body). This shader was compiled and checked in Chrome (ANGLE/SwiftShader) over a photo backdrop.
precision highp float;
uniform sampler2D uBackdrop; uniform vec2 uRes; uniform vec4 uRect;
uniform float uRadius, uBezel, uDisp, uFrost, uTime;
uniform int uProfile; // 0 bevel, 1 convex, 2 rim
varying vec2 vUv; // 0..1, y down (upload the texture without FLIP_Y)
float sdRoundBox(vec2 p, vec2 b, float r) { vec2 q = abs(p) - b + r; return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; }
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
vec3 tex(vec2 px) { return texture2D(uBackdrop, clamp(px / uRes, 0.0, 1.0)).rgb; }
// Backdrop shift across the bezel; s = depth into the bezel (0 edge .. 1 inner end); edge = 1.
// Same curves as the TypeScript BEND table: bevel (1-s)^2, convex dome, rim = the bevel over the outer 35 %.
float bendAt(float s) {
float a = 1.0 - s;
if (uProfile == 1) return a * (1.0 + a) * 0.5;
if (uProfile == 2) { float u = max(1.0 - s / 0.35, 0.0); return u * u; }
return a * a;
}
void main() {
vec2 px = vUv * uRes;
vec2 c = uRect.xy + uRect.zw * 0.5, hb = uRect.zw * 0.5;
float d = sdRoundBox(px - c, hb, uRadius); // < 0 inside
vec3 back = tex(px), col = back;
if (d < 1.0) {
float depth = clamp(-d / uBezel, 0.0, 1.0);
vec2 e = vec2(0.5, 0.0);
vec2 n = normalize(vec2(sdRoundBox(px - c + e.xy, hb, uRadius) - sdRoundBox(px - c - e.xy, hb, uRadius),
sdRoundBox(px - c + e.yx, hb, uRadius) - sdRoundBox(px - c - e.yx, hb, uRadius)));
float bend = depth < 1.0 ? bendAt(depth) : 0.0;
vec2 off = -n * bend * uDisp; // inward
off += (vec2(hash(px), hash(px + 17.0)) - 0.5) * 1.5 * uFrost; // frost grain (uFrost 0 = clear lens, 1 = frost)
float k = 0.02 * bend * bend; // dispersion: the split grows as bend³, so it stays at the rim
vec3 bent = vec3(tex(px + off * (1.0 - k)).r, tex(px + off).g, tex(px + off * (1.0 + k)).b);
vec3 blur = (tex(px + off + vec2(2.0, 0.0)) + tex(px + off - vec2(2.0, 0.0)) +
tex(px + off + vec2(0.0, 2.0)) + tex(px + off - vec2(0.0, 2.0))) * 0.25;
vec3 g = mix(bent, blur, 0.35 * uFrost);
g = mix(g, vec3(dot(g, vec3(0.299, 0.587, 0.114))), -0.4); // saturation x1.4
g = mix(g, vec3(1.0), 0.10); // fill (white 10 %)
vec2 L = normalize(vec2(-1.0, -1.0)); // key light top-left (y down)
float facing = dot(n, L);
float rim = 1.0 - smoothstep(0.0, 1.5, -d); // 1 px rim
g += rim * mix(0.5, 0.9, max(facing, 0.0)) * (facing > 0.0 ? 1.0 : 0.55);
g += (1.0 - smoothstep(0.0, 0.35, depth)) * max(facing, 0.0) * 0.18; // inner glow
col = mix(back, g, clamp(0.5 - d, 0.0, 1.0)); // anti-aliased silhouette
}
gl_FragColor = vec4(col, 1.0);
}Effect building blocks for the same shader (add, don't replace, the glass above):
// Caustics: animated Worley cell borders, two layers multiplied.
vec2 hash2(vec2 p) { p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3))); return fract(sin(p) * 43758.5453); }
float cells(vec2 uv, float t) {
vec2 g = floor(uv), f = fract(uv); float d1 = 8.0, d2 = 8.0;
for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
vec2 o = vec2(float(x), float(y)), h = hash2(g + o);
vec2 r = o + 0.5 + 0.45 * sin(t + 6.2831 * h) - f; float dd = dot(r, r);
if (dd < d1) { d2 = d1; d1 = dd; } else if (dd < d2) { d2 = dd; }
}
return pow(1.0 - smoothstep(0.0, 0.3, sqrt(d2) - sqrt(d1)), 3.0);
}
float caustics(vec2 uv, float t) { return cells(uv * 4.0, t) * cells(uv * 6.5 + 3.1, t * 1.3) * 2.5; }
// Iridescence (thin film): hue shifts with viewing angle / surface normal.
vec3 thinFilm(float cosTheta, float thickness) {
return 0.5 + 0.5 * cos(6.2831 * (thickness * (1.0 - cosTheta) + vec3(0.0, 0.33, 0.67)));
}
// Morph: smooth union of two glass shapes (merge radius k in px).
float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }Use smin(sdA, sdB, 24.0) as the glass distance to get liquid merging when two bodies approach; derive the normal from the merged distance exactly as above, but scale the offset by the raw gradient instead of the normalised normal (vec2 g = vec2(dx, dy); n = g / max(length(g), 1e-4); off = -g * bend * uDisp;). The gradient's length is 1 on a single shape and falls to 0 at the neck, where the two lobes' normals cancel; normalised, the offset flips there in one pixel and the backdrop tears into a vertical step.
D. Liquid metal accent (WebGL, not glass)
Opaque chrome for the one metal element in a view (liquid-metal effect spec). Nothing behind is sampled, so it is a separate pass: a transparent canvas laid over the element (pointer-events: none, sized in device px), blend gl.ONE, gl.ONE_MINUS_SRC_ALPHA, one draw per metal shape with the same full-screen quad and vUv as the glass shader; labels stay in the DOM above it. uRing 2–4 px (× devicePixelRatio) draws only the rim of a button or the ring of a selected tile; uRing = 0 fills an icon or logo mark. uBands 2–2.5 for rims, 1.2–1.6 for fills. Checked in headless Chrome on dark and light pages.
// Liquid metal accent: opaque chrome bands drawn over the page; nothing behind is sampled.
precision highp float;
uniform vec2 uRes; uniform vec4 uRect; // canvas px; shape rect x, y, w, h in px (y down)
uniform float uRadius; // corner radius px (h / 2 for a capsule or circle)
uniform float uRing; // rim width px; 0 fills the whole shape (icon, logo mark)
uniform float uBands; // reflection bands across the shape: 2–2.5 rim, 1.2–1.6 fill
uniform float uShift; // red/blue channel shift: 0 none, 0.2–0.35 UI, up to 0.6 logo marks
uniform float uAngle; // band direction in radians (1.2 ≈ 70°)
uniform float uTime; // seconds; keep it fixed under reduced motion
varying vec2 vUv; // 0..1, y down
float sdRoundBox(vec2 p, vec2 b, float r) { vec2 q = abs(p) - b + r; return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; }
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
float noise(vec2 p) {
vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y);
}
// One reflection band: thin white strip, thin dark strip, white again, then a long soft ramp from dark to light.
float band(float x) {
const float s = 0.025; // band-edge softness (fraction of a band)
float v = 0.98;
v = mix(v, 0.07, smoothstep(0.10, 0.10 + s, x));
v = mix(v, 0.98, smoothstep(0.16, 0.16 + s, x));
return mix(v, mix(0.10, 0.85, smoothstep(0.22, 1.0, x)), smoothstep(0.22, 0.22 + s, x));
}
void main() {
vec2 px = vUv * uRes;
vec2 c = uRect.xy + uRect.zw * 0.5, hb = uRect.zw * 0.5, p = px - c;
float d = sdRoundBox(p, hb, uRadius); // < 0 inside
float a = clamp(0.5 - d, 0.0, 1.0);
if (uRing > 0.0) a *= clamp(0.5 + d + uRing, 0.0, 1.0); // keep only the rim band
if (a <= 0.0) discard;
float size = min(hb.x, hb.y);
vec2 q = p / size;
float edge = uRing > 0.0 ? 1.0 : 1.0 - smoothstep(0.0, 0.5 * size, -d); // 1 at the silhouette
float s = dot(q, vec2(cos(uAngle), sin(uAngle))) * 0.5; // bands run across the shape
s += 0.35 * edge * edge; // and bend where the surface turns away
s += 0.08 * noise(q * 1.2 + uTime * 0.12); // slow liquid wobble
s = s * uBands - uTime * 0.08; // drift: about 12 s per band
float k = uShift * 0.05 * (0.4 + edge); // fringes grow toward the silhouette
vec3 v = vec3(band(fract(s + k)), band(fract(s)), band(fract(s - 1.3 * k)));
vec3 col = mix(vec3(0.08, 0.085, 0.10), vec3(0.97, 0.975, 1.0), v);
col *= 0.92 + 0.12 * clamp(-q.y, -1.0, 1.0); // a little brighter toward the top
gl_FragColor = vec4(col * a, a); // premultiplied alpha
}The Paper Shaders LiquidMetal React component (@paper-design/shaders-react) renders the same material from a built-in shape or a transparent logo image: repetition 2, softness 0.1, shiftRed / shiftBlue 0.3, distortion 0.07, contour 0.4; speed 0 plus a fixed frame for a still.
Static fallback without WebGL (no fringes):
.metal-rim { position: relative; border-radius: 999px; }
.metal-rim::before {
content: ""; position: absolute; inset: 0; padding: 3px; border-radius: inherit; pointer-events: none;
background: conic-gradient(from 200deg, #14151a 0 7%, #f7f8fc 10% 21%, #8a8d96 30%, #fff 43% 47%,
#2a2b30 51% 59%, #d9dbe2 70%, #14151a 81%, #f7f8fc 92%);
-webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
-webkit-mask-composite: xor; mask-composite: exclude;
}E. Border beam (animated rim light)
One beamed element per view (border-beam effect spec). The beam is a sibling layer between the rim and the content of the glass body from A2: the optic never refracts it, and it is no ancestor of the optic, so it creates no backdrop root (A4 rule 7). Checked in headless Chrome on the A2 glass with the SVG refraction, over photos and the grid.
<div class="glass" style="--radius:30px">
<span class="glass__optic"></span>
<span class="glass__glow"></span>
<span class="glass__rim"></span>
<span class="glass__bloom" aria-hidden="true"><span class="glass__beam"><i></i></span></span> <!-- optional glow -->
<span class="glass__beam" aria-hidden="true"><i></i></span> <!-- twin beams: add <i style="--beam-start:.5"></i> -->
<span class="glass__content">Get started</span>
</div>.glass { --beam-width: 1.5px; --beam-length: 84px; --beam-lap: 5s;
--beam-head: #fff; --beam-mid: rgba(255,255,255,.5); }
/* A ring as wide as the beam: the layer minus its content box. */
.glass__beam { pointer-events: none; padding: var(--beam-width);
-webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
-webkit-mask-composite: xor;
mask: linear-gradient(#000 0 0) content-box exclude, linear-gradient(#000 0 0); }
/* One streak rides the outline at constant speed. offset-rotate: auto (the default) turns it with the path, so the
bright end of its gradient always leads. */
.glass__beam > i { position: absolute; left: 0; top: 0; width: var(--beam-length); aspect-ratio: 1;
background: linear-gradient(to left, var(--beam-head), var(--beam-mid) 30%, transparent);
offset-path: inset(0 round var(--radius));
animation: glass-beam var(--beam-lap) linear infinite;
animation-delay: calc(var(--beam-lap) * var(--beam-start, 0) * -1); }
@keyframes glass-beam { from { offset-distance: 0%; } to { offset-distance: 100%; } }
/* Bloom: the same beam 3 px wide, blurred by a wrapper. A filter on the masked layer itself runs before the mask
and is cut into a hard grey band. */
.glass__bloom { pointer-events: none; filter: blur(4px); opacity: .8; }
.glass__bloom > .glass__beam { position: absolute; inset: 0; border-radius: inherit; --beam-width: 3px; }
@media (prefers-reduced-motion: reduce) { .glass__beam { display: none; } }- Light glass:
--beam-head: #2b6bff; --beam-mid: rgba(43,107,255,.45); --beam-width: 2px. A white beam disappears into a light rim. - Sizes: buttons
--beam-length≈ 1.5 × the height and a 4–6 s lap; cards 120–200 px and 6–10 s; a working state 2–3 s. Keep--beam-length≤ 1.5 × the shorter side: a longer square reaches across a thin capsule and lights the opposite edge as well. - Longer tails on thin shapes (a comet over 20–35 % of a capsule): replace the single streak with n = 10–16 lagging segments,
<i style="--k:0"></i> … <i style="--k:15"></i>in<div class="glass__beam glass__beam--comet" style="--n:16; --beam-tail:.3; --beam-seg:24px">, where--beam-seg≈ 2 × the tail in px / n:
.glass__beam--comet > i { width: var(--beam-seg); background: var(--beam-head);
opacity: calc((1 - var(--k) / var(--n)) * (1 - var(--k) / var(--n)));
animation-delay: calc(var(--beam-lap) * (var(--k) / var(--n) * var(--beam-tail) - 1 - var(--beam-start, 0))); }- Distance, not angle. A
conic-gradient(from var(--angle))spun through@propertyis the common shortcut, but it is driven by angle: on a capsule the beam crawls mid-edge and races, stretched, round the caps (referenceborder-beam-speed-by-distance-vs-angle). Use it only on shapes up to about 1.5 : 1. inset(0 round R)must use the body'sborder-radius. For another outline (squircle,corner-shape), useoffset-path: path("…")of that outline.- Browser support:
offset-pathbasic shapes need Chrome 116, Safari 18, Firefox 122. Where it is missing the streak sits still in the top-left corner; hide.glass__beambehind@supports (offset-path: inset(0))if that matters.
Shader version (Tier C): add to the glass shader of section C. rimPos turns a pixel into its position along the outline, so the beam keeps one speed and length on any rounded box. Compiled and checked in Chrome (ANGLE/SwiftShader) on a 800 × 120 capsule at seven lap phases.
// Border beam: arc-length position (0-1, clockwise from the top-left end of the top edge, y down) of the
// outline point nearest to p, for a rounded box centred at the origin with half size b and corner radius r.
float rimPos(vec2 p, vec2 b, float r) {
vec2 s = max(b - r, 0.0), q = clamp(p, -s, s), v = p - q; // v: from the straight skeleton out to p
float a = atan(v.y, v.x), h = 1.5707963 * r, d; // a: clockwise from +x (y down)
// Pick the quarter by the signs of v, never by comparing a: on straight edges a is exactly +-pi/2 or pi.
if (v.x >= 0.0 && v.y <= 0.0) d = q.x + s.x + r * (a + 1.5707963) + q.y + s.y; // top, top-right, right
else if (v.x >= 0.0) d = 2.0 * (s.x + s.y) + h + r * a + s.x - q.x; // bottom-right, bottom
else if (v.y >= 0.0) d = 4.0 * s.x + 2.0 * s.y + 2.0 * h + r * (a - 1.5707963) + s.y - q.y; // bottom-left, left
else d = 4.0 * (s.x + s.y) + 3.0 * h + r * (a + 3.1415927); // top-left
return d / (4.0 * (s.x + s.y) + 4.0 * h);
}
// 0..1 beam intensity: `width` px just inside the edge (sd < 0 inside), bright head at lap phase t, fading over
// `tail` (fraction of the perimeter) behind it. Constant speed along the outline, whatever the aspect ratio.
float borderBeam(vec2 p, vec2 b, float r, float sd, float t, float tail, float width) {
float behind = fract(t - rimPos(p, b, r));
float along = 1.0 - clamp(behind / tail, 0.0, 1.0);
float across = smoothstep(-width - 0.75, -width + 0.75, sd) * (1.0 - smoothstep(-0.75, 0.75, sd));
return along * along * across;
}In main(), after the rim and glow lines and before the silhouette mix: g += borderBeam(px - c, hb, uRadius, d, fract(uTime / 5.0), 0.25, 1.5) * vec3(1.0); (the accent colour on light glass).
F. Materialize and touch illumination
Glass that comes and goes gains its optics instead of fading (materialize effect spec), and pressing lights it from under the finger (touch-illumination). Both work on bodies mounted with mountGlass (M); the A2 fill already takes --materialize.
/**
* Shows or hides a glass body by growing or shrinking its optics: the bend (the filter's displacement), the rim and
* glow, and the fill rise together over `ms`; the content settles in over the last part. Under Reduce Motion it is a
* short cross-fade instead. `glass` is what mountGlass returned.
*/
export function materialize(glass, { show = true, ms = 260 } = {}) {
const { el } = glass;
if (matchMedia("(prefers-reduced-motion: reduce)").matches) {
el.hidden = false;
el.animate([{ opacity: show ? 0 : 1 }, { opacity: show ? 1 : 0 }], { duration: 150, fill: "forwards" })
.finished.then(() => { if (!show) el.hidden = true; });
return;
}
el.hidden = false;
// The filter may be redrawn on the way (a new size, a press): each frame scales the current one from its own full
// value, kept on it the first time it is seen.
const bend = (m) => {
const fe = glass.filter()?.querySelector("feDisplacementMap");
if (!fe) return;
fe.dataset.full ??= fe.getAttribute("scale");
fe.setAttribute("scale", String(Number(fe.dataset.full) * m));
};
const t0 = performance.now();
const step = (now) => {
const t = Math.min(1, (now - t0) / ms), eased = 1 - (1 - t) ** 3, m = show ? eased : 1 - eased;
bend(m);
el.style.setProperty("--materialize", String(m)); // rim, glow, fill and content follow (A2 + the CSS below)
if (t < 1) requestAnimationFrame(step);
else if (!show) el.hidden = true;
};
requestAnimationFrame(step);
}
/**
* Lights glass from under the finger: a soft glow at the touch point spreads through the pressed body, and glass
* within 24 px gets a quarter of it on the side facing the touch. Call once for the page.
*/
export function touchLight(root = document) {
const light = (body, x, y, strength) => {
let layer = body.querySelector(":scope > .glass__light");
if (!layer) {
layer = Object.assign(document.createElement("span"), { className: "glass__light" });
body.querySelector(":scope > .glass__content")?.before(layer);
}
layer.style.setProperty("--touch-x", `${x}%`);
layer.style.setProperty("--touch-y", `${y}%`);
layer.style.setProperty("--touch-strength", String(strength));
body.classList.add("is-lit");
};
root.addEventListener("pointerdown", (e) => {
const body = e.target.closest?.(".glass");
if (!body) return;
const r = body.getBoundingClientRect();
light(body, ((e.clientX - r.left) / r.width) * 100, ((e.clientY - r.top) / r.height) * 100, 1);
for (const n of root.querySelectorAll(".glass")) {
if (n === body || n.contains(body) || body.contains(n)) continue;
const q = n.getBoundingClientRect();
const gap = Math.max(q.left - r.right, r.left - q.right, q.top - r.bottom, r.top - q.bottom);
if (gap < 0 || gap > 24) continue;
const clamp = (v) => Math.min(100, Math.max(0, v));
light(n, clamp(((e.clientX - q.left) / q.width) * 100), clamp(((e.clientY - q.top) / q.height) * 100), 0.25);
}
});
const off = () => root.querySelectorAll(".glass.is-lit").forEach((b) => b.classList.remove("is-lit"));
for (const type of ["pointerup", "pointercancel"]) addEventListener(type, off);
}/* Materialize: rim, glow and content follow --materialize (0 = plain backdrop, 1 = full glass; the fill takes it in A2),
1 when nothing sets it. */
.glass > .glass__rim, .glass > .glass__glow { opacity: var(--materialize, 1); }
.glass > .glass__content { opacity: clamp(0, calc(var(--materialize, 1) * 2.5 - 1.5), 1); }
/* Touch illumination: a soft white glow from the touch point, shown while pressed. */
.glass__light { pointer-events: none; opacity: 0; transition: opacity .3s ease-out;
background: radial-gradient(circle at var(--touch-x, 50%) var(--touch-y, 50%), rgba(255,255,255,.36), rgba(255,255,255,.12) 45%, transparent 75%); }
.glass.is-lit > .glass__light { opacity: var(--touch-strength, 1); transition-duration: .25s; }Usage: materialize(mountGlass(toolbar, {…}), { show: false }) on scroll down, { show: true } on scroll up; touchLight() once, after mounting.
G. Background extension and light spill
A hero beside a floating sidebar or inspector continues under it as its own edge, flipped and blurred (background-extension), and large glass takes the colour of the content beside it into its glow and shadow (light-spill).
<div class="split" style="--hero: url(hero.jpg); --sidebar-w: 280px">
<div class="split__extend"></div> <!-- under the sidebar -->
<img class="split__hero" src="hero.jpg" alt="">
<nav class="sidebar glass--frost glass--spill" style="--spill: #c86fb0"><span class="glass__content">…</span></nav>
</div>/* G. Background extension: a hero beside a floating sidebar. The hero's edge, flipped at the seam and blurred, fills
the strip under the sidebar, so the glass bends a continuation of the hero instead of a cut or a page colour. */
.split { position: relative; display: grid; grid-template-columns: var(--sidebar-w, 280px) 1fr; overflow: hidden; }
.split__hero { grid-column: 2; grid-row: 1; width: 100%; height: 100%; object-fit: cover; object-position: left center; display: block; }
.split__extend { grid-column: 1; grid-row: 1; position: relative; overflow: hidden; }
.split__extend::before { content: ""; position: absolute; inset: -48px; transform: scaleX(-1);
/* the hero at its own height, its left edge at the seam once flipped */
background: var(--hero) left center / auto 100% no-repeat; filter: blur(32px) saturate(1.15); }
.split > .sidebar { position: absolute; left: 10px; top: 10px; bottom: 10px; width: calc(var(--sidebar-w, 280px) - 20px); }
/* Light spill: the content's colour (--spill) in the glow and the shadow on the side facing it (--spill-side: negative
when the content is to the right). Large glass only. */
.glass--spill { box-shadow: 0 0 0 1px var(--glass-edge), 0 8px 28px color-mix(in srgb, var(--spill) 12%, rgba(0, 0, 0, .14)); }
.glass--spill > .glass__glow { box-shadow: inset 2px 3px 8px -4px var(--glass-glow-key), inset -2px -3px 8px -4px var(--glass-glow-counter),
inset var(--spill-side, -14px) 0 22px -10px color-mix(in srgb, var(--spill) 18%, transparent); }Mount the sidebar with mountGlass (M) as a frost panel (radius 24, bezel 24, displacement 9.6, blur 12, squircle). Set --spill to the content's main colour when it changes, not on every scroll frame.
QA. Check it in a browser
Headless Chrome renders the SVG filters, so screenshots are a valid check. Serve the page from a local server and run this script with the page's address; it saves light and dark shots of the page, the bend with the blur down to 0.5 px (thin lines must curve inside every bezel, the centre calm, nothing doubled), the clear and tinted ends and the frost fallback, and it measures every label and icon on glass against the pixels behind it at all three fill levels. Pass the scroll positions where a photo or the brightest content passes under a floating bar: that is the worst case. A screen that does not scroll (a camera, a player) has states instead: give each one a URL parameter (zoom, mode, an open menu) and run the script once per state, and give a moving backdrop (video, a live scene) a parameter that holds one frame, so every run measures the same pixels.
// qa.mjs — screenshot QA for liquid glass on the web. For light and dark it saves the page, the bend with the blur
// turned down, the clear and tinted ends and the frost fallback, and measures every label and icon on glass against
// the pixels behind it at the default fill and at both ends, at each scroll position given (a photo or the brightest
// content under a floating bar is the worst case). Exit code 1 when nothing bends or a label misses contrast.
// npm i -D playwright (uses the installed Chrome; else `npx playwright install chromium`)
// node qa.mjs <the page's address on your local server> [width] [height] [scroll positions, e.g. 0,900,1800]
import { chromium } from "playwright";
const [url, w = "390", h = "844", at = "0"] = process.argv.slice(2);
if (!url) throw new Error("Usage: node qa.mjs <the page's address on your local server> [width] [height] [scroll positions]");
const positions = at.split(",").map(Number);
const browser = await chromium.launch({ channel: "chrome" }).catch(() => chromium.launch());
let failed = false;
for (const colorScheme of ["light", "dark"]) {
const page = await browser.newPage({ viewport: { width: +w, height: +h }, deviceScaleFactor: 2, colorScheme });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("response", (r) => r.status() >= 400 && !r.url().endsWith("/favicon.ico") && errors.push(`${r.status()} ${r.url()}`));
await page.goto(url, { waitUntil: "networkidle" });
await page.waitForTimeout(600);
const shot = (name) => page.screenshot({ path: `qa-${colorScheme}-${name}.png` });
// Every glass body should carry its SVG filter (Chromium is the engine that bends).
const bodies = await page.evaluate(() => [...document.querySelectorAll(".glass__optic")]
.filter((o) => o.checkVisibility?.({ visibilityProperty: true }) !== false && o.getClientRects().length)
.map((o) => /url\(/.test(getComputedStyle(o).backdropFilter)));
await shot("page");
// The ends of the clear-to-tinted setting: every fill halved and doubled (A2 --glass-amount).
for (const [name, amount] of [["clear", "0.5"], ["tinted", "2"]]) {
await page.evaluate((a) => document.documentElement.style.setProperty("--glass-amount", a), amount);
await shot(name);
}
await page.evaluate(() => document.documentElement.style.removeProperty("--glass-amount"));
// The bend with the blur down to 0.5 px: lines must curve inside every bezel, the centre calm, nothing doubled.
const blurs = await page.evaluate(() => [...document.querySelectorAll("feGaussianBlur")].map((b) => {
const v = b.getAttribute("stdDeviation");
b.setAttribute("stdDeviation", "0.5");
return v;
}));
await page.waitForTimeout(200);
await shot("bend");
await page.evaluate((v) => document.querySelectorAll("feGaussianBlur").forEach((b, i) => b.setAttribute("stdDeviation", v[i])), blurs);
await page.waitForTimeout(200);
// Contrast: each label (4.5:1, 3:1 when large) and icon (3:1) on glass against what is behind it, text hidden, at the
// default fill and at the clear end. The box of the glyphs themselves (a Range over the text, the icon's own box).
// A label another glass body covers (content scrolled under a floating bar) is skipped, not failed.
const targetsNow = () => page.evaluate(() => [...document.querySelectorAll(".glass__content, .glass__content *")].flatMap((el) => {
const cs = getComputedStyle(el), size = parseFloat(cs.fontSize), body = el.closest(".glass");
const boxes = el.localName === "svg"
? [{ r: el.getBoundingClientRect(), need: 3, label: `icon (${(el.closest("[aria-label]")?.getAttribute("aria-label") ||
el.parentElement.textContent.trim()).slice(0, 24) || el.parentElement.localName})` }]
: [...el.childNodes].filter((n) => n.nodeType === 3 && n.textContent.trim()).map((n) => {
const range = document.createRange();
range.selectNodeContents(n);
return { r: range.getBoundingClientRect(), label: n.textContent.trim().slice(0, 24), need: size >= 24 || (size >= 18.66 && +cs.fontWeight >= 700) ? 3 : 4.5 };
});
// Not what a reader sees: hidden, inert (under a modal), aria-hidden, or screen-reader-only text.
const own = el.getBoundingClientRect();
if (own.width <= 1 || own.height <= 1 || el.closest("[inert], [aria-hidden='true'], [hidden]") ||
el.checkVisibility?.({ visibilityProperty: true, opacityProperty: true }) === false) return [];
return boxes.filter(({ r }) => {
if (r.width < 2 || r.height < 2 || r.bottom < 0 || r.top > innerHeight) return false;
const top = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2)?.closest(".glass");
return !top || top === body || top.contains(body) || body.contains(top);
}).map(({ r, label, need }) => ({ label, need, color: cs.color, x: r.x, y: r.y, w: r.width, h: r.height }));
}));
const measure = async (amount, targets) => {
await page.evaluate((a) => document.documentElement.style.setProperty("--glass-amount", a), amount);
const hide = await page.addStyleTag({ content: ".glass__content, .glass__content * { color: transparent !important; text-shadow: none !important; } .glass__content svg { visibility: hidden !important; }" });
await page.waitForTimeout(150);
const behind = (await page.screenshot()).toString("base64");
await hide.evaluate((n) => n.remove());
await page.evaluate(() => document.documentElement.style.removeProperty("--glass-amount"));
return page.evaluate(async ({ behind, targets }) => {
const img = await createImageBitmap(await (await fetch(`data:image/png;base64,${behind}`)).blob());
const c = new OffscreenCanvas(img.width, img.height), ctx = c.getContext("2d");
ctx.drawImage(img, 0, 0);
const k = img.width / innerWidth;
const lum = (r, g, b) => [r, g, b].map((v) => { v /= 255; return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; })
.reduce((s, v, i) => s + v * [0.2126, 0.7152, 0.0722][i], 0);
return targets.map((t) => {
const [r, g, b, a = 1] = t.color.match(/[\d.]+/g).map(Number);
const x0 = Math.max(0, Math.round(t.x * k)), y0 = Math.max(0, Math.round(t.y * k));
const px = ctx.getImageData(x0, y0, Math.max(1, Math.min(Math.round(t.w * k), img.width - x0)), Math.max(1, Math.min(Math.round(t.h * k), img.height - y0))).data;
const all = [];
for (let i = 0; i < px.length; i += 4) {
const bl = lum(px[i], px[i + 1], px[i + 2]);
const fl = lum(r * a + px[i] * (1 - a), g * a + px[i + 1] * (1 - a), b * a + px[i + 2] * (1 - a));
all.push((Math.max(bl, fl) + 0.05) / (Math.min(bl, fl) + 0.05));
}
all.sort((p, q) => p - q);
return all[Math.floor(all.length * 0.02)];
});
}, { behind, targets });
};
const ratios = [];
for (const y of positions) {
await page.evaluate((top) => scrollTo(0, top), y);
await page.waitForTimeout(250);
const targets = await targetsNow();
const ends = [["default", await measure("1", targets)], ["clear end", await measure("0.5", targets)], ["tinted end", await measure("2", targets)]];
targets.forEach((t, i) => {
const [end, ratio] = ends.map(([e, r]) => [e, r[i]]).sort((p, q) => p[1] - q[1])[0];
ratios.push({ label: t.label, need: t.need, ratio, end: positions.length > 1 ? `${end}, scroll ${y}` : end });
});
}
await page.evaluate(() => scrollTo(0, 0));
// The frost fallback that Safari and Firefox show.
await page.evaluate(() => {
document.documentElement.classList.add("glass-frost-only");
document.querySelectorAll(".glass__optic").forEach((o) => o.style.removeProperty("--glass-filter"));
});
await page.waitForTimeout(200);
await shot("fallback");
const flat = bodies.filter((b) => !b).length;
const low = ratios.filter((r) => r.ratio < r.need).sort((p, q) => p.ratio - q.ratio);
const worst = [...ratios].sort((p, q) => p.ratio / p.need - q.ratio / q.need)[0];
console.log(`${colorScheme}: ${bodies.length} glass bodies, ${bodies.length - flat} with the bend filter` +
(worst ? ` · lowest contrast ${worst.ratio.toFixed(2)}:1 ("${worst.label}" at the ${worst.end}, needs ${worst.need})` : "") +
(errors.length ? ` · page errors: ${errors.slice(0, 3).join(" | ")}` : ""));
for (const r of low) console.log(` contrast ${r.ratio.toFixed(2)}:1 < ${r.need} at the ${r.end} — "${r.label}"`);
// A body without the filter is either flat on purpose (a knob at rest) or broken: look at it in the bend shot.
if (!bodies.length || flat === bodies.length || low.length || errors.length) failed = true;
await page.close();
}
await browser.close();
console.log(`Saved qa-{light,dark}-{page,clear,tinted,bend,fallback}.png${failed ? " · FAILED" : ""}`);
process.exitCode = failed ? 1 : 0;Look at the bend shots for the curve and the page shots for the rim (brighter top-left, dark edge line outside). The fallback shot simulates Safari and Firefox inside Chrome; open the page in them when you can. A body the script counts without the filter is either flat on purpose (a knob at rest) or broken.
<!-- medium: swiftui -->
Questions
Can CSS alone make liquid glass?
Not the bend. backdrop-filter: blur() only frosts the backdrop. The bend needs an SVG filter with a displacement map, applied with backdrop-filter: url(#id), which only Chromium browsers render inside backdrop-filter.
Does it work in Safari and Firefox?
They show the frost fallback (blur, saturation, fill and rim) with no bend. For a bend in every browser, draw the glass in WebGL over a known backdrop, as in section C.
Why not feTurbulence noise?
Noise wobbles the whole surface like water. Glass is still in the middle and bends only within its bezel; the displacement map here is computed from the shape's edge, so straight lines curve once, at the rim.
How do I keep it fast?
Cache one map per size, round animated sizes to a few steps, and drop the filter from bodies that are off screen. Rules A4 cover the details.
The rules behind it
The code is half of it. Where glass belongs, which material each body gets, how it stays legible and what to reject are in the liquid glass guide and the 34 component specs. Other platforms: SwiftUI, Flutter, React Native, Figma.