Skip to content

Liquid Glass

Liquid Glass for React: a lens that refracts what is behind it, with squircle bevel, specular rim, dispersion and spring physics.

  • Liquid Glass
  • Media & publishing
  • React only · 0 deps
  • 1 file
Full screen

Browser support · Real refraction (SVG displacement inside backdrop-filter) in Chromium browsers. Safari and Firefox fall back to a frosted blur with the same rim and highlights.

Install. One command, or copy the file.

$npx shadcn@latest add https://freedesignmd.com/r/liquid-glass.json
  • Byte-identical to the preview
  • No Tailwind or config needed
  • SSR-safe · keyboard accessible
  • Respects reduced motion & transparency
components/liquid-glass/liquid-glass.tsx
1/**
2 * LiquidGlass, Apple's Liquid Glass material, rebuilt for the web.
3 *
4 * A surface for controls and navigation that float ABOVE content. It bends
5 * what is behind it like a real glass slab: a convex squircle bevel refracts
6 * the backdrop (Snell's law, IOR 1.5) so lines and text bend near the rim
7 * while the centre stays flat and readable; a light-facing specular rim, a
8 * faint counter-light, slight chromatic dispersion and a touch glow finish it.
9 *
10 * <LiquidGlass
11 * as="button" // any element, default "div"
12 * variant="regular" // "regular" (blur + luminosity, for text) | "clear" (over photos/video)
13 * tone="light" // regular only: "light" | "dark" foreground/fill scheme
14 * radius="capsule" // "capsule" | number (px), keep radii concentric
15 * tint="#007AFF" // optional accent tint (glassProminent)
16 * dim // clear only: 35% dark dimming layer for bright content
17 * interactive // springy press, pointer highlight, touch glow
18 * bezel={20} refraction={1} dispersion={0.05} blur={8}
19 * />
20 *
21 * Also exported: Spring (tiny rAF spring integrator), useSpring,
22 * useReducedMotion, useGlassEnv, stretchTransform, createVelocityTracker,
23 * GlassScope (render the stylesheet once for many glass elements).
24 *
25 * Browser support: real refraction uses an SVG displacement filter inside
26 * `backdrop-filter: url(#…)`, which only Chromium (Chrome, Edge, Arc, Brave,
27 * Opera) supports. Safari and Firefox get a tuned frosted recipe (blur +
28 * saturate + brightness) with the same specular rim and highlights.
29 * Accessibility: purely visual; pass real elements via `as` (button, nav…).
30 * Honors prefers-reduced-transparency (opaque frosted fill),
31 * prefers-contrast: more (opaque + solid border) and prefers-reduced-motion
32 * (no spring/scale, glow fades only).
33 */
34import { createContext, forwardRef, useContext, useEffect, useId, useImperativeHandle, useLayoutEffect, useRef, useState } from "react";
35import type { AllHTMLAttributes, CSSProperties, ElementType, ReactNode } from "react";
36
37export type GlassVariant = "regular" | "clear";
38export type GlassTone = "light" | "dark";
39
40export interface LiquidGlassProps extends Omit<AllHTMLAttributes<HTMLElement>, "as"> {
41 /** Element to render. Default "div". */
42 as?: ElementType;
43 /** "regular" blurs + adjusts luminosity (use with text); "clear" is highly translucent (use over rich media). */
44 variant?: GlassVariant;
45 /** Regular variant colour scheme. Clear always uses light-on-dark foreground. Default "light". */
46 tone?: GlassTone;
47 /** Corner radius in px, "capsule" (default), or "auto", read from the element's own border-radius (use for animated morphs). */
48 radius?: number | "capsule" | "auto";
49 /** Accent tint colour (any CSS colour), makes the glass "prominent". */
50 tint?: string;
51 /** Adds the 35% dark dimming layer HIG asks for when clear glass sits on bright content. */
52 dim?: boolean;
53 /** Press bounce, pointer-following highlight and touch glow. */
54 interactive?: boolean;
55 /** Scale while pressed (interactive only). Default 0.96. Use >1 for "lift". */
56 pressScale?: number;
57 /** Width of the refracting bevel in px. Default ≈ 26% of the short side (6–40px). */
58 bezel?: number;
59 /** Refraction strength multiplier. Default 1. */
60 refraction?: number;
61 /** Chromatic dispersion 0–0.3. Default 0.05. */
62 dispersion?: number;
63 /** Backdrop blur in px. Defaults: regular 8, clear 0.6. */
64 blur?: number;
65 /** Drop shadow under the glass. Default true. */
66 shadow?: boolean;
67 children?: ReactNode;
68}
69
70/* ───────────────────────── environment ───────────────────────── */
71
72const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
73
74type GlassEnv = { refraction: boolean; reducedMotion: boolean; reducedTransparency: boolean };
75const SSR_ENV: GlassEnv = { refraction: false, reducedMotion: false, reducedTransparency: false };
76
77function detectChromium(): boolean {
78 const nav = navigator as Navigator & { userAgentData?: { brands?: { brand: string }[] } };
79 const brands = nav.userAgentData?.brands?.map((b) => b.brand).join(" ") ?? "";
80 if (/Chromium|Google Chrome|Microsoft Edge|Opera|Brave/i.test(brands)) return true;
81 const ua = nav.userAgent;
82 return /\b(Chrome|Chromium|HeadlessChrome)\/\d/.test(ua) && !/Firefox|FxiOS/.test(ua);
83}
84
85/** Runtime capabilities. SSR-safe: everything is false until mounted. */
86export function useGlassEnv(): GlassEnv {
87 const [env, setEnv] = useState<GlassEnv>(SSR_ENV);
88 useEffect(() => {
89 const mm = (q: string) => window.matchMedia(q);
90 const rm = mm("(prefers-reduced-motion: reduce)");
91 const rt = mm("(prefers-reduced-transparency: reduce)");
92 const hc = mm("(prefers-contrast: more)");
93 const read = () =>
94 setEnv({
95 refraction: detectChromium() && !rt.matches && !hc.matches,
96 reducedMotion: rm.matches,
97 reducedTransparency: rt.matches || hc.matches,
98 });
99 read();
100 [rm, rt, hc].forEach((q) => q.addEventListener?.("change", read));
101 return () => [rm, rt, hc].forEach((q) => q.removeEventListener?.("change", read));
102 }, []);
103 return env;
104}
105
106export function useReducedMotion(): boolean {
107 return useGlassEnv().reducedMotion;
108}
109
110/* ───────────────────────── physics ───────────────────────── */
111
112export type SpringConfig = { stiffness?: number; damping?: number; mass?: number; precision?: number };
113
114/** Semi-implicit Euler spring integrated in rAF. Drives transforms through `onUpdate`. */
115export class Spring {
116 value: number;
117 target: number;
118 velocity = 0;
119 stiffness: number;
120 damping: number;
121 mass: number;
122 precision: number;
123 private raf = 0;
124 private last = 0;
125 constructor(value: number, public onUpdate: (v: number, s: Spring) => void, cfg: SpringConfig = {}) {
126 this.value = this.target = value;
127 this.stiffness = cfg.stiffness ?? 380;
128 this.damping = cfg.damping ?? 30;
129 this.mass = cfg.mass ?? 1;
130 this.precision = cfg.precision ?? 0.001;
131 }
132 /** Animate to `target`, optionally injecting a velocity (units/s). */
133 to(target: number, velocity?: number) {
134 this.target = target;
135 if (velocity !== undefined) this.velocity = velocity;
136 if (!this.raf && typeof requestAnimationFrame !== "undefined") {
137 this.last = performance.now();
138 this.raf = requestAnimationFrame(this.tick);
139 }
140 }
141 /** Jump without animating. */
142 set(v: number) {
143 this.stop();
144 this.value = this.target = v;
145 this.velocity = 0;
146 this.onUpdate(v, this);
147 }
148 stop() {
149 if (this.raf) cancelAnimationFrame(this.raf);
150 this.raf = 0;
151 }
152 get active() {
153 return this.raf !== 0;
154 }
155 private tick = (now: number) => {
156 const dt = Math.min(Math.max((now - this.last) / 1000, 0), 1 / 30);
157 this.last = now;
158 const steps = 4;
159 const h = dt / steps;
160 for (let i = 0; i < steps; i++) {
161 const f = -this.stiffness * (this.value - this.target) - this.damping * this.velocity;
162 this.velocity += (f / this.mass) * h;
163 this.value += this.velocity * h;
164 }
165 const p = this.precision;
166 if (Math.abs(this.velocity) < p * 10 && Math.abs(this.value - this.target) < p) {
167 this.value = this.target;
168 this.velocity = 0;
169 this.raf = 0;
170 this.onUpdate(this.value, this);
171 return;
172 }
173 this.onUpdate(this.value, this);
174 this.raf = requestAnimationFrame(this.tick);
175 };
176}
177
178/** A stable Spring for the component's lifetime. `onUpdate` may change between renders. */
179export function useSpring(initial: number, onUpdate: (v: number) => void, cfg?: SpringConfig): Spring {
180 const cb = useRef(onUpdate);
181 cb.current = onUpdate;
182 const ref = useRef<Spring | null>(null);
183 if (!ref.current) ref.current = new Spring(initial, (v) => cb.current(v), cfg);
184 useEffect(() => () => ref.current?.stop(), []);
185 return ref.current;
186}
187
188/** Area-preserving stretch along a velocity vector (px/s). */
189export function stretchTransform(vx: number, vy: number, gain = 0.00018, max = 0.32): string {
190 const speed = Math.hypot(vx, vy);
191 if (speed < 1) return "";
192 const a = Math.atan2(vy, vx);
193 const s = 1 + Math.min(max, speed * gain);
194 return `rotate(${a}rad) scale(${s}, ${1 / s}) rotate(${-a}rad)`;
195}
196
197/** Tracks pointer velocity (px/s) over the last ~80ms. */
198export function createVelocityTracker() {
199 let samples: { x: number; y: number; t: number }[] = [];
200 return {
201 reset() {
202 samples = [];
203 },
204 push(x: number, y: number, t = performance.now()) {
205 samples.push({ x, y, t });
206 while (samples.length > 2 && t - samples[0].t > 80) samples.shift();
207 },
208 get(): { vx: number; vy: number } {
209 if (samples.length < 2) return { vx: 0, vy: 0 };
210 const a = samples[0];
211 const b = samples[samples.length - 1];
212 const dt = Math.max((b.t - a.t) / 1000, 1 / 240);
213 return { vx: (b.x - a.x) / dt, vy: (b.y - a.y) / dt };
214 },
215 };
216}
217
218/* ───────────────────────── optics: displacement + specular maps ───────────────────────── */
219
220const LUT_N = 512;
221let LUT: { disp: Float32Array; nxy: Float32Array; nz: Float32Array } | null = null;
222
223/** Convex squircle bevel, t: 0 at the rim → 1 where the slab becomes flat. */
224const surface = (t: number) => Math.pow(1 - Math.pow(1 - t, 4), 0.25);
225const surfaceSlope = (t: number) => {
226 const tt = Math.min(Math.max(t, 1e-4), 1);
227 return Math.pow(1 - tt, 3) * Math.pow(1 - Math.pow(1 - tt, 4), -0.75);
228};
229
230function lut() {
231 if (LUT) return LUT;
232 const disp = new Float32Array(LUT_N);
233 const nxy = new Float32Array(LUT_N);
234 const nz = new Float32Array(LUT_N);
235 const IOR = 1.5;
236 let max = 0;
237 for (let i = 0; i < LUT_N; i++) {
238 const t = i / (LUT_N - 1);
239 const s = surfaceSlope(t);
240 const theta = Math.atan(s); // angle of the surface normal from vertical
241 const refr = Math.asin(Math.sin(theta) / IOR); // Snell
242 const thickness = 0.55 + surface(t); // base slab + bevel height (in bezel units)
243 const d = Math.tan(theta - refr) * thickness;
244 disp[i] = d;
245 max = Math.max(max, d);
246 const l = Math.hypot(s, 1);
247 nxy[i] = s / l;
248 nz[i] = 1 / l;
249 }
250 for (let i = 0; i < LUT_N; i++) disp[i] /= max;
251 LUT = { disp, nxy, nz };
252 return LUT;
253}
254
255const sample = (arr: Float32Array, t: number) => {
256 const f = Math.min(Math.max(t, 0), 1) * (LUT_N - 1);
257 const i = Math.floor(f);
258 const j = Math.min(i + 1, LUT_N - 1);
259 return arr[i] + (arr[j] - arr[i]) * (f - i);
260};
261
262let canvas: HTMLCanvasElement | null = null;
263
264/**
265 * Builds the displacement map (R,G = dx,dy around 128) and the specular rim
266 * image for a w×h rounded rect. Returns data URLs.
267 */
268export function renderGlassMaps(w: number, h: number, radius: number, bezel: number, dpr = 1, draft = false) {
269 const L = lut();
270 if (!canvas) canvas = document.createElement("canvas");
271 const ctx = canvas.getContext("2d");
272 if (!ctx) return null;
273 const hw = w / 2;
274 const hh = h / 2;
275 const r = Math.min(radius, hw, hh);
276 const rn = Math.min(Math.max(r, bezel), hw, hh); // inflated radius → crease-free normals
277
278 const build = (scale: number, kind: "disp" | "spec") => {
279 const mw = Math.max(2, Math.round(w * scale));
280 const mh = Math.max(2, Math.round(h * scale));
281 canvas!.width = mw;
282 canvas!.height = mh;
283 const img = ctx.createImageData(mw, mh);
284 const data = img.data;
285 // light from the top-left, a faint counter light from the bottom-right
286 const l1x = -0.5, l1y = -0.72, l1z = 0.48;
287 const l2x = 0.55, l2y = 0.7, l2z = 0.45;
288 for (let j = 0; j < mh; j++) {
289 const py = (j + 0.5) / scale - hh;
290 const ay = Math.abs(py);
291 for (let i = 0; i < mw; i++) {
292 const px = (i + 0.5) / scale - hw;
293 const ax = Math.abs(px);
294 const o = (j * mw + i) * 4;
295 // signed distance to the true rounded rect (negative inside)
296 const qx = ax - hw + r;
297 const qy = ay - hh + r;
298 const dist = qx > 0 && qy > 0 ? Math.hypot(qx, qy) - r : Math.max(qx, qy) - r;
299 const inside = -dist;
300 if (kind === "disp") {
301 data[o + 2] = 128;
302 data[o + 3] = 255;
303 }
304 if (inside <= 0 || inside >= bezel) {
305 if (kind === "disp") {
306 data[o] = 128;
307 data[o + 1] = 128;
308 }
309 continue;
310 }
311 const t = inside / bezel;
312 // outward normal from the inflated rounded rect
313 const nx0 = ax - hw + rn;
314 const ny0 = ay - hh + rn;
315 let nx: number, ny: number;
316 if (nx0 > 0 && ny0 > 0) {
317 const l = Math.hypot(nx0, ny0);
318 nx = nx0 / l;
319 ny = ny0 / l;
320 } else if (nx0 > ny0) {
321 nx = 1;
322 ny = 0;
323 } else {
324 nx = 0;
325 ny = 1;
326 }
327 if (px < 0) nx = -nx;
328 if (py < 0) ny = -ny;
329 if (kind === "disp") {
330 const m = sample(L.disp, t);
331 // sample inward: content near the rim is pulled from inside the slab
332 data[o] = Math.round(128 - nx * m * 127);
333 data[o + 1] = Math.round(128 - ny * m * 127);
334 } else {
335 const sxy = sample(L.nxy, t);
336 const sz = sample(L.nz, t);
337 const Nx = nx * sxy, Ny = ny * sxy, Nz = sz;
338 const d1 = Math.max(0, Nx * l1x + Ny * l1y + Nz * l1z);
339 const d2 = Math.max(0, Nx * l2x + Ny * l2y + Nz * l2z);
340 const rim = Math.pow(sxy, 7); // grazing fresnel line right at the edge
341 const a = Math.min(1, 0.95 * Math.pow(d1, 5) * sxy + 0.42 * Math.pow(d2, 5) * sxy + 0.22 * rim);
342 data[o] = 255;
343 data[o + 1] = 255;
344 data[o + 2] = 255;
345 data[o + 3] = Math.round(a * 255);
346 }
347 }
348 }
349 ctx.putImageData(img, 0, 0);
350 return canvas!.toDataURL("image/png");
351 };
352
353 const base = Math.min(1, (draft ? 300 : 520) / Math.max(w, h));
354 const disp = build(base, "disp");
355 const specScale = draft ? base : Math.min(Math.min(dpr, 2), 1100 / Math.max(w, h));
356 const spec = build(specScale, "spec");
357 return { disp, spec };
358}
359
360/* ───────────────────────── styles ───────────────────────── */
361
362const ScopeCtx = createContext(false);
363
364/** Renders the glass stylesheet once for every LiquidGlass inside it. */
365export function GlassScope({ children }: { children: ReactNode }) {
366 return (
367 <ScopeCtx.Provider value>
368 <style>{GLASS_CSS}</style>
369 {children}
370 </ScopeCtx.Provider>
371 );
372}
373
374/* ───────────────────────── component ───────────────────────── */
375
376export const LiquidGlass = forwardRef<HTMLElement, LiquidGlassProps>(function LiquidGlass(
377 {
378 as: Tag = "div",
379 variant = "regular",
380 tone = "light",
381 radius = "capsule",
382 tint,
383 dim = false,
384 interactive = false,
385 pressScale = 0.96,
386 bezel,
387 refraction = 1,
388 dispersion = 0.05,
389 blur,
390 shadow = true,
391 className,
392 style,
393 children,
394 ...rest
395 },
396 ref,
397) {
398 const scoped = useContext(ScopeCtx);
399 const rawId = useId();
400 const fid = "fd-lg-" + rawId.replace(/[^a-zA-Z0-9_-]/g, "");
401 const el = useRef<HTMLElement | null>(null);
402 const specEl = useRef<HTMLSpanElement | null>(null);
403 const feImg = useRef<SVGFEImageElement | null>(null);
404 const dR = useRef<SVGFEDisplacementMapElement | null>(null);
405 const dG = useRef<SVGFEDisplacementMapElement | null>(null);
406 const dB = useRef<SVGFEDisplacementMapElement | null>(null);
407 useImperativeHandle(ref, () => el.current as HTMLElement);
408 const env = useGlassEnv();
409
410 // keep live params in a ref so the observer never needs re-subscribing
411 const params = useRef({ radius, bezel, refraction, dispersion, refract: env.refraction });
412 params.current = { radius, bezel, refraction, dispersion, refract: env.refraction };
413
414 /* displacement + specular maps, regenerated on size change only */
415 useIsoLayoutEffect(() => {
416 const node = el.current;
417 if (!node) return;
418 let raf = 0;
419 let timer = 0;
420 let lastKey = "";
421 const apply = (draft = false) => {
422 raf = 0;
423 const w = node.offsetWidth;
424 const h = node.offsetHeight;
425 if (w < 4 || h < 4) return;
426 const p = params.current;
427 const rad =
428 p.radius === "capsule"
429 ? Math.min(w, h) / 2
430 : Math.min(p.radius === "auto" ? parseFloat(getComputedStyle(node).borderTopLeftRadius) || 0 : p.radius, w / 2, h / 2);
431 const bz = Math.max(4, Math.min(p.bezel ?? Math.min(Math.max(Math.min(w, h) * 0.26, 6), 40), Math.min(w, h) / 2));
432 const dpr = Math.min(window.devicePixelRatio || 1, 2);
433 const key = [w, h, rad, bz, dpr].join(":");
434 if (key !== lastKey) {
435 const maps = renderGlassMaps(w, h, rad, bz, dpr, draft);
436 if (!maps) return;
437 if (!draft) lastKey = key;
438 if (specEl.current) specEl.current.style.backgroundImage = `url("${maps.spec}")`;
439 feImg.current?.setAttribute("href", maps.disp);
440 }
441 const scale = bz * 0.9 * p.refraction * 2;
442 const disp = Math.min(Math.max(p.dispersion, 0), 0.3);
443 for (const [e, k] of [[dR.current, 1 - disp], [dG.current, 1], [dB.current, 1 + disp]] as const) e?.setAttribute("scale", String(scale * k));
444 if (p.refract) node.style.setProperty("--fd-lg-url", `url(#${fid})`);
445 else node.style.removeProperty("--fd-lg-url");
446 };
447 let first = true;
448 const onResize = () => {
449 feImg.current?.setAttribute("width", String(node.offsetWidth));
450 feImg.current?.setAttribute("height", String(node.offsetHeight));
451 if (first) {
452 first = false;
453 return;
454 }
455 // live resize (morphs, springs): cheap low-res map in the same frame (ResizeObserver
456 // runs before paint), full quality once the size settles
457 apply(true);
458 window.clearTimeout(timer);
459 timer = window.setTimeout(() => {
460 cancelAnimationFrame(raf);
461 raf = requestAnimationFrame(() => apply(false));
462 }, 120);
463 };
464 onResize();
465 apply(false);
466 const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(onResize) : null;
467 ro?.observe(node);
468 return () => {
469 ro?.disconnect();
470 cancelAnimationFrame(raf);
471 window.clearTimeout(timer);
472 };
473 }, [fid, radius, bezel, refraction, dispersion, env.refraction]);
474
475 /* interaction: press spring, pointer highlight, touch glow */
476 const press = useSpring(1, (v) => el.current?.style.setProperty("--fd-lg-s", v.toFixed(4)), { stiffness: 520, damping: 22 });
477 useEffect(() => {
478 const node = el.current;
479 if (!node || !interactive) return;
480 const pos = (e: PointerEvent) => {
481 const r = node.getBoundingClientRect();
482 const s = Number(node.style.getPropertyValue("--fd-lg-s")) || 1;
483 node.style.setProperty("--fd-lg-mx", `${((e.clientX - r.left) / s).toFixed(1)}px`);
484 node.style.setProperty("--fd-lg-my", `${((e.clientY - r.top) / s).toFixed(1)}px`);
485 };
486 const down = (e: PointerEvent) => {
487 if ((node as HTMLButtonElement).disabled || node.getAttribute("aria-disabled") === "true") return;
488 pos(e);
489 node.classList.add("fd-lg--pressed");
490 node.classList.remove("fd-lg--released");
491 if (env.reducedMotion) return;
492 press.stiffness = 900;
493 press.damping = 48;
494 press.to(pressScale);
495 };
496 const up = () => {
497 if (!node.classList.contains("fd-lg--pressed")) return;
498 node.classList.remove("fd-lg--pressed");
499 node.classList.add("fd-lg--released");
500 if (env.reducedMotion) return;
501 press.stiffness = 420;
502 press.damping = 14;
503 press.to(1, (1 - pressScale) * 18);
504 };
505 const key = (e: KeyboardEvent) => {
506 if (e.repeat || (e.key !== " " && e.key !== "Enter")) return;
507 node.style.setProperty("--fd-lg-mx", "50%");
508 node.style.setProperty("--fd-lg-my", "50%");
509 node.classList.add("fd-lg--pressed");
510 if (!env.reducedMotion) {
511 press.stiffness = 900;
512 press.damping = 48;
513 press.to(pressScale);
514 }
515 };
516 const keyUp = (e: KeyboardEvent) => {
517 if (e.key === " " || e.key === "Enter") up();
518 };
519 node.addEventListener("pointermove", pos);
520 node.addEventListener("pointerdown", down);
521 node.addEventListener("pointerenter", pos);
522 window.addEventListener("pointerup", up);
523 window.addEventListener("pointercancel", up);
524 node.addEventListener("keydown", key);
525 node.addEventListener("keyup", keyUp);
526 node.addEventListener("blur", up);
527 return () => {
528 node.removeEventListener("pointermove", pos);
529 node.removeEventListener("pointerdown", down);
530 node.removeEventListener("pointerenter", pos);
531 window.removeEventListener("pointerup", up);
532 window.removeEventListener("pointercancel", up);
533 node.removeEventListener("keydown", key);
534 node.removeEventListener("keyup", keyUp);
535 node.removeEventListener("blur", up);
536 };
537 }, [interactive, pressScale, env.reducedMotion, press]);
538
539 const vars: Record<string, string | number> = {};
540 if (radius !== "auto") vars["--fd-lg-r"] = radius === "capsule" ? "9999px" : `${radius}px`;
541 if (blur !== undefined) vars["--fd-lg-blur"] = `${blur}px`;
542 if (tint) vars["--fd-lg-tint"] = tint;
543
544 const cls = [
545 "fd-lg",
546 `fd-lg--${variant}`,
547 variant === "regular" ? `fd-lg--${tone}` : "fd-lg--dark",
548 tint ? "fd-lg--tinted" : "",
549 dim ? "fd-lg--dim" : "",
550 interactive ? "fd-lg--interactive" : "",
551 shadow ? "" : "fd-lg--flat",
552 env.refraction ? "fd-lg--refract" : "",
553 className ?? "",
554 ]
555 .filter(Boolean)
556 .join(" ");
557
558 return (
559 <Tag ref={el} className={cls} style={{ ...(vars as CSSProperties), ...style }} {...rest}>
560 {!scoped && <style>{GLASS_CSS}</style>}
561 <svg className="fd-lg-svg" aria-hidden="true" focusable="false" width="0" height="0">
562 <filter id={fid} colorInterpolationFilters="sRGB">
563 <feImage ref={feImg} x="0" y="0" width="1" height="1" preserveAspectRatio="none" result="map" />
564 <feDisplacementMap ref={dR} in="SourceGraphic" in2="map" scale="0" xChannelSelector="R" yChannelSelector="G" result="dr" />
565 <feColorMatrix in="dr" type="matrix" values="1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0" result="r" />
566 <feDisplacementMap ref={dG} in="SourceGraphic" in2="map" scale="0" xChannelSelector="R" yChannelSelector="G" result="dg" />
567 <feColorMatrix in="dg" type="matrix" values="0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0" result="g" />
568 <feDisplacementMap ref={dB} in="SourceGraphic" in2="map" scale="0" xChannelSelector="R" yChannelSelector="G" result="db" />
569 <feColorMatrix in="db" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0" result="b" />
570 <feComposite in="r" in2="g" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" result="rg" />
571 <feComposite in="rg" in2="b" operator="arithmetic" k1="0" k2="1" k3="1" k4="0" />
572 </filter>
573 </svg>
574 <span className="fd-lg-layer fd-lg-fill" aria-hidden="true" />
575 {dim && <span className="fd-lg-layer fd-lg-dimmer" aria-hidden="true" />}
576 <span ref={specEl} className="fd-lg-layer fd-lg-spec" aria-hidden="true" />
577 <span className="fd-lg-layer fd-lg-edge" aria-hidden="true" />
578 {interactive && <span className="fd-lg-layer fd-lg-glow" aria-hidden="true" />}
579 {children}
580 </Tag>
581 );
582});
583
584/* ───────────────────────── demo ───────────────────────── */
585
586const LENS = 184;
587
588export function Demo() {
589 const stage = useRef<HTMLDivElement | null>(null);
590 const lens = useRef<HTMLElement | null>(null);
591 const env = useGlassEnv();
592
593 const paint = () => {
594 const node = lens.current;
595 if (!node) return;
596 const st = env.reducedMotion ? "" : stretchTransform(sx.velocity, sy.velocity, 0.00022, 0.28);
597 node.style.setProperty("--fd-lg-pre", `translate(${sx.value.toFixed(2)}px, ${sy.value.toFixed(2)}px) ${st}`);
598 };
599 const sx = useSpring(0, paint, { stiffness: 380, damping: 30 });
600 const sy = useSpring(0, paint, { stiffness: 380, damping: 30 });
601
602 const bounds = () => {
603 const s = stage.current!;
604 return { maxX: Math.max(0, s.clientWidth - LENS), maxY: Math.max(0, s.clientHeight - LENS) };
605 };
606
607 // start centred, a little off to the left so the lens straddles the shapes
608 useEffect(() => {
609 const s = stage.current;
610 if (!s) return;
611 sx.set(s.clientWidth / 2 - LENS / 2 - 36);
612 sy.set(s.clientHeight / 2 - LENS / 2 + 4);
613 const onResize = () => {
614 const b = bounds();
615 sx.to(Math.min(Math.max(sx.target, 0), b.maxX));
616 sy.to(Math.min(Math.max(sy.target, 0), b.maxY));
617 };
618 window.addEventListener("resize", onResize);
619 return () => window.removeEventListener("resize", onResize);
620 // eslint-disable-next-line react-hooks/exhaustive-deps
621 }, []);
622
623 // dragging with elastic stretch and a springy throw
624 useEffect(() => {
625 const node = lens.current;
626 if (!node) return;
627 const vt = createVelocityTracker();
628 let dragging = false;
629 let ox = 0, oy = 0;
630 const down = (e: PointerEvent) => {
631 if (e.button !== 0) return;
632 node.setPointerCapture(e.pointerId);
633 dragging = true;
634 ox = e.clientX - sx.value;
635 oy = e.clientY - sy.value;
636 vt.reset();
637 vt.push(e.clientX, e.clientY);
638 sx.stiffness = sy.stiffness = env.reducedMotion ? 4000 : 700;
639 sx.damping = sy.damping = env.reducedMotion ? 130 : 42;
640 };
641 const move = (e: PointerEvent) => {
642 if (!dragging) return;
643 vt.push(e.clientX, e.clientY);
644 const b = bounds();
645 const rb = (v: number, max: number) => (v < 0 ? v * 0.35 : v > max ? max + (v - max) * 0.35 : v);
646 sx.to(rb(e.clientX - ox, b.maxX));
647 sy.to(rb(e.clientY - oy, b.maxY));
648 };
649 const up = () => {
650 if (!dragging) return;
651 dragging = false;
652 const { vx, vy } = vt.get();
653 const b = bounds();
654 const k = env.reducedMotion ? 0 : 0.11;
655 sx.stiffness = sy.stiffness = 260;
656 sx.damping = sy.damping = 20;
657 sx.to(Math.min(Math.max(sx.target + vx * k, 0), b.maxX), env.reducedMotion ? 0 : vx * 0.4);
658 sy.to(Math.min(Math.max(sy.target + vy * k, 0), b.maxY), env.reducedMotion ? 0 : vy * 0.4);
659 };
660 const key = (e: KeyboardEvent) => {
661 const step = e.shiftKey ? 64 : 20;
662 const d: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
663 const v = d[e.key];
664 if (!v) return;
665 e.preventDefault();
666 const b = bounds();
667 sx.stiffness = sy.stiffness = 380;
668 sx.damping = sy.damping = 30;
669 sx.to(Math.min(Math.max(sx.target + v[0], 0), b.maxX));
670 sy.to(Math.min(Math.max(sy.target + v[1], 0), b.maxY));
671 };
672 node.addEventListener("pointerdown", down);
673 node.addEventListener("pointermove", move);
674 node.addEventListener("pointerup", up);
675 node.addEventListener("pointercancel", up);
676 node.addEventListener("keydown", key);
677 return () => {
678 node.removeEventListener("pointerdown", down);
679 node.removeEventListener("pointermove", move);
680 node.removeEventListener("pointerup", up);
681 node.removeEventListener("pointercancel", up);
682 node.removeEventListener("keydown", key);
683 };
684 // eslint-disable-next-line react-hooks/exhaustive-deps
685 }, [env.reducedMotion]);
686
687 return (
688 <div className="fd-lgx" ref={stage}>
689 <style>{DEMO_CSS}</style>
690 <span className="fd-lgx-shape fd-lgx-shape--a" aria-hidden="true" />
691 <span className="fd-lgx-shape fd-lgx-shape--b" aria-hidden="true" />
692 <span className="fd-lgx-shape fd-lgx-shape--c" aria-hidden="true" />
693 <GlassScope>
694 <LiquidGlass
695 ref={lens}
696 as="div"
697 role="button"
698 tabIndex={0}
699 aria-label="Glass lens. Drag it, or use the arrow keys to move it."
700 className="fd-lgx-lens"
701 variant="clear"
702 radius={LENS / 2}
703 interactive
704 pressScale={1.06}
705 refraction={1.2}
706 dispersion={0.08}
707 />
708 </GlassScope>
709 </div>
710 );
711}
712
713const FONT = `ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif`;
714
715const DEMO_CSS = `
716.fd-lgx,.fd-lgx *,.fd-lgx *::before,.fd-lgx *::after{box-sizing:border-box}
717.fd-lgx{position:relative;height:100vh;min-height:520px;width:100%;overflow:hidden;margin:0;padding:0;color:#1d1d1f;font:400 15px/1.4 ${FONT};letter-spacing:normal;touch-action:none;
718 background:radial-gradient(46% 62% at 28% 32%,#ffcfa6 0%,transparent 70%),radial-gradient(44% 58% at 74% 68%,#b7c3ff 0%,transparent 70%),radial-gradient(30% 40% at 62% 22%,#ffc2dc 0%,transparent 70%),#f1eeea}
719.fd-lgx-shape{position:absolute;display:block;margin:0;padding:0;pointer-events:none}
720.fd-lgx-shape--a{left:calc(50% - 190px);top:calc(50% - 70px);width:150px;height:150px;border-radius:50%;background:#ff8a6b}
721.fd-lgx-shape--b{left:calc(50% - 20px);top:calc(50% - 130px);width:150px;height:150px;border-radius:38px;background:#5b6cff;transform:rotate(14deg)}
722.fd-lgx-shape--c{left:calc(50% - 30px);top:calc(50% + 40px);width:210px;height:34px;border-radius:999px;background:#fff}
723.fd-lgx-lens{position:absolute;left:0;top:0;width:${LENS}px;height:${LENS}px;border-radius:50%;cursor:grab;touch-action:none;will-change:transform;z-index:2}
724.fd-lgx-lens.fd-lg--pressed{cursor:grabbing}
725`;
726
727const GLASS_CSS = `
728.fd-lg{
729 --fd-ease-out:cubic-bezier(0.22,1,0.36,1);--fd-ease-in-out:cubic-bezier(0.65,0,0.35,1);--fd-spring:cubic-bezier(0.34,1.56,0.64,1);
730 --fd-dur-1:120ms;--fd-dur-2:240ms;--fd-dur-3:420ms;--fd-dur-4:700ms;
731 --fd-lg-url:blur(0px);
732 --fd-lg-blur:8px;--fd-lg-sat:1.8;--fd-lg-bright:1.06;--fd-lg-contrast:0.92;
733 --fd-lg-fill:rgba(255,255,255,0.30);
734 --fd-lg-fg:#0B0B0F;
735 --fd-lg-edge-a:rgba(255,255,255,0.95);--fd-lg-edge-b:rgba(255,255,255,0.18);--fd-lg-edge-c:rgba(255,255,255,0.55);
736 --fd-lg-shadow:0 12px 32px -10px rgba(10,10,20,0.28),0 2px 6px -1px rgba(10,10,20,0.10);
737 --fd-lg-spec-o:0.9;
738 isolation:isolate;box-sizing:border-box;margin:0;border:0;
739 background:transparent;color:var(--fd-lg-fg);text-decoration:none;
740 -webkit-appearance:none;appearance:none;-webkit-tap-highlight-color:transparent;
741 -webkit-backdrop-filter:blur(var(--fd-lg-blur)) saturate(var(--fd-lg-sat)) brightness(var(--fd-lg-bright)) contrast(var(--fd-lg-contrast));
742 backdrop-filter:var(--fd-lg-url) blur(var(--fd-lg-blur)) saturate(var(--fd-lg-sat)) brightness(var(--fd-lg-bright)) contrast(var(--fd-lg-contrast));
743 box-shadow:var(--fd-lg-shadow);
744}
745:where(.fd-lg){position:relative;padding:0;border-radius:var(--fd-lg-r,0px);font:500 15px/1.25 ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif;letter-spacing:normal;text-align:center}
746.fd-lg *,.fd-lg *::before,.fd-lg *::after{box-sizing:border-box}
747.fd-lg--flat{--fd-lg-shadow:none}
748.fd-lg--regular.fd-lg--dark{--fd-lg-fill:rgba(30,30,36,0.42);--fd-lg-fg:#FFFFFF;--fd-lg-bright:0.92;--fd-lg-edge-a:rgba(255,255,255,0.55);--fd-lg-edge-b:rgba(255,255,255,0.08);--fd-lg-edge-c:rgba(255,255,255,0.28);--fd-lg-spec-o:0.55;--fd-lg-shadow:0 14px 36px -12px rgba(0,0,0,0.6),0 2px 6px -1px rgba(0,0,0,0.3)}
749.fd-lg--clear{--fd-lg-blur:0.5px;--fd-lg-sat:1.3;--fd-lg-bright:1.03;--fd-lg-contrast:1;--fd-lg-fill:rgba(255,255,255,0.05);--fd-lg-fg:#FFFFFF;--fd-lg-spec-o:1;--fd-lg-shadow:0 10px 30px -10px rgba(0,0,0,0.35),0 1px 3px rgba(0,0,0,0.12);text-shadow:0 1px 2px rgba(0,0,0,0.28)}
750.fd-lg--clear:not(.fd-lg--refract){--fd-lg-blur:2.5px;--fd-lg-sat:1.5;--fd-lg-fill:rgba(255,255,255,0.12)}
751.fd-lg--regular:not(.fd-lg--refract){--fd-lg-blur:16px}
752.fd-lg--tinted{--fd-lg-fg:#FFFFFF;text-shadow:none}
753.fd-lg--tinted.fd-lg--regular{--fd-lg-fill:color-mix(in srgb,var(--fd-lg-tint) 84%,transparent)}
754.fd-lg--tinted.fd-lg--clear{--fd-lg-fill:color-mix(in srgb,var(--fd-lg-tint) 58%,transparent)}
755.fd-lg-svg{position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;display:block;margin:0;padding:0;border:0}
756.fd-lg-layer{position:absolute;inset:0;z-index:-1;display:block;margin:0;padding:0;border:0;border-radius:inherit;pointer-events:none;background:none}
757.fd-lg-fill{background:var(--fd-lg-fill);box-shadow:inset 0 0 18px -6px rgba(255,255,255,0.22)}
758.fd-lg-dimmer{background:rgba(0,0,0,0.35)}
759.fd-lg-spec{background-size:100% 100%;background-repeat:no-repeat;opacity:var(--fd-lg-spec-o);transition:opacity var(--fd-dur-2) var(--fd-ease-out)}
760.fd-lg-edge{padding:1px;background:linear-gradient(140deg,var(--fd-lg-edge-a),var(--fd-lg-edge-b) 34%,var(--fd-lg-edge-b) 62%,var(--fd-lg-edge-c));
761 -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)}
762.fd-lg--interactive{transform:var(--fd-lg-pre,translate(0,0)) scale(var(--fd-lg-s,1));cursor:pointer;touch-action:manipulation}
763.fd-lg-glow{opacity:0;transition:opacity var(--fd-dur-3) var(--fd-ease-out);
764 background:radial-gradient(circle at var(--fd-lg-mx,50%) var(--fd-lg-my,50%),rgba(255,255,255,0.55),rgba(255,255,255,0.14) 38%,transparent 70%);
765 background-size:100% 100%;mix-blend-mode:plus-lighter}
766.fd-lg--interactive:hover .fd-lg-glow{opacity:0.35}
767.fd-lg--pressed .fd-lg-glow{opacity:1;transition-duration:var(--fd-dur-1)}
768.fd-lg--released .fd-lg-glow{transition-duration:var(--fd-dur-4)}
769.fd-lg:focus-visible{outline:2px solid color-mix(in srgb,#0A84FF 70%,transparent);outline-offset:2px}
770.fd-lg[disabled],.fd-lg[aria-disabled="true"]{cursor:default}
771@media (prefers-reduced-transparency: reduce){
772 .fd-lg{-webkit-backdrop-filter:none;backdrop-filter:none;text-shadow:none}
773 .fd-lg .fd-lg-fill{background:#ECECF0}
774 .fd-lg--dark .fd-lg-fill{background:#2A2A31}
775 .fd-lg--tinted .fd-lg-fill{background:var(--fd-lg-tint)}
776 .fd-lg--regular.fd-lg--light:not(.fd-lg--tinted){--fd-lg-fg:#0B0B0F}
777 .fd-lg-spec{opacity:0.25}
778 .fd-lg-dimmer{display:none}
779}
780@media (prefers-contrast: more){
781 .fd-lg{-webkit-backdrop-filter:none;backdrop-filter:none;text-shadow:none}
782 .fd-lg .fd-lg-fill{background:#FFFFFF}
783 .fd-lg--dark .fd-lg-fill{background:#000000}
784 .fd-lg--tinted .fd-lg-fill{background:var(--fd-lg-tint)}
785 .fd-lg--regular.fd-lg--light:not(.fd-lg--tinted){--fd-lg-fg:#000000}
786 .fd-lg-spec,.fd-lg-dimmer{display:none}
787 .fd-lg-edge{-webkit-mask:none;mask:none;background:none;box-shadow:inset 0 0 0 1px rgba(0,0,0,0.75)}
788 .fd-lg--dark .fd-lg-edge{box-shadow:inset 0 0 0 1px rgba(255,255,255,0.8)}
789}
790@media (prefers-reduced-motion: reduce){
791 .fd-lg--interactive{transform:var(--fd-lg-pre,none)}
792 .fd-lg-glow{transition-duration:var(--fd-dur-1)}
793}
794`;

More Liquid Glass. Same file contract.

Glass Button, liquid glass preview: Liquid Glass button for React: glass, prominent, clear and clear-prominent capsules in four sizes, with a…

Glass Button

Liquid Glass button for React: glass, prominent, clear and clear-prominent capsules in four sizes, with a springy press.

Glass Tab Bar, liquid glass preview: iOS 26 style Liquid Glass tab bar: a lens springs between tabs, search sits apart, and the bar minimizes as…

Glass Tab Bar

iOS 26 style Liquid Glass tab bar: a lens springs between tabs, search sits apart, and the bar minimizes as you scroll.

Glass Toggle, liquid glass preview: Liquid Glass toggle switch in the iOS 26 style: the knob swells into clear glass while pressed or dragged,…

Glass Toggle

Liquid Glass toggle switch in the iOS 26 style: the knob swells into clear glass while pressed or dragged, then settles.

Questions about Liquid Glass

Run npx shadcn@latest add https://freedesignmd.com/r/liquid-glass.json, or open the page and copy the file into your project. It has zero dependencies besides React. What you copy is the exact file that renders the live demo.

Liquid Glass for React: a lens that refracts what is behind it, with squircle bevel, specular rim, dispersion and spring physics. It is a free, MIT-licensed React liquid glass component from the freedesignmd library.

Yes. It is free and MIT-licensed, use, modify and ship it in personal and commercial projects without attribution.

Real refraction (SVG displacement inside backdrop-filter) in Chromium browsers. Safari and Firefox fall back to a frosted blur with the same rim and highlights.

Yes. It is a plain React component with its own styles, so it runs in Next.js, Vite, Remix and Lovable projects, and it needs no Tailwind setup. It has zero dependencies besides React.