Paper patterns
Quiet CSS-only surface patterns for sections, cards and preview stages: diagonal hatch in both directions, cross-hatch, a graph grid with minor and major lines, ruled notebook lines with an optional margin rule, an isometric triangle grid, fine grain noise and a blueprint grid on a tinted base. Lines are drawn from your border, muted and primary colours, so they follow the theme in light and dark. Patterns take a scale in pixels and an opacity, can line up with the element's edge, content box or centre, and can fade into the page from the centre, top, bottom or edges. Use the wrapper component, or the style helper to put a pattern on any element. The pattern layer is decorative and hidden from assistive technology, and nothing moves.
Source
import type { CSSProperties, ElementType, ReactNode } from "react";
import { cn } from "@/lib/utils";
export type Pattern = "hatch" | "hatch-reverse" | "cross-hatch" | "graph" | "ruled" | "isometric" | "grain" | "blueprint";
export type Fade = "none" | "center" | "top" | "bottom" | "edges";
export const PATTERNS: Pattern[] = ["hatch", "hatch-reverse", "cross-hatch", "graph", "ruled", "isometric", "grain", "blueprint"];
export type PatternOptions = {
/** Size of one repeat in px (minor grid, line spacing, triangle side). */
scale?: number;
/** 0 to 1, multiplies the pattern's own (already quiet) strength. */
opacity?: number;
/** "edge" starts lines at the element's top-left corner, "content" at its content box, "center" in the middle. */
origin?: "edge" | "content" | "center";
/** Ruled only: draw the margin rule. */
margin?: boolean;
};
const DEFAULT_SCALE: Record<Pattern, number> = {
hatch: 10, "hatch-reverse": 10, "cross-hatch": 12, graph: 16, ruled: 28, isometric: 24, grain: 160, blueprint: 20,
};
const mix = (color: string, amount: number) => `color-mix(in oklab, ${color} ${Math.round(amount * 100)}%, transparent)`;
/* A 1px line along one diagonal of the tile: "to top right" joins the top-left and bottom-right corners. */
function diagonal(direction: string, color: string) {
return `linear-gradient(${direction}, transparent calc(50% - 0.6px), ${color} calc(50% - 0.6px) calc(50% + 0.6px), transparent calc(50% + 0.6px))`;
}
function grainUri(alpha: number) {
const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='3' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 ${(alpha * 2.2).toFixed(3)} ${(-alpha * 0.55).toFixed(3)}'/></filter><rect width='100%' height='100%' filter='url(#n)'/></svg>`;
return `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;
}
/** Background properties for a pattern, safe to spread onto any element's style. */
export function patternStyle(pattern: Pattern, options: PatternOptions = {}): CSSProperties {
const s = Math.max(4, options.scale ?? DEFAULT_SCALE[pattern]);
const k = Math.min(1, Math.max(0, options.opacity ?? 1));
const line = mix("var(--border)", k);
const strong = mix("var(--muted-foreground)", 0.32 * k);
const position = options.origin === "center" ? "center" : "0 0";
const origin = options.origin === "content" ? "content-box" : "padding-box";
const base = { backgroundPosition: position, backgroundOrigin: origin } as CSSProperties;
switch (pattern) {
// Diagonals are drawn corner to corner inside square tiles, which keeps every line the same weight.
case "hatch":
return { ...base, backgroundImage: diagonal("to bottom right", strong), backgroundSize: `${s}px ${s}px` };
case "hatch-reverse":
return { ...base, backgroundImage: diagonal("to top right", strong), backgroundSize: `${s}px ${s}px` };
case "cross-hatch":
return { ...base, backgroundImage: `${diagonal("to bottom right", strong)}, ${diagonal("to top right", strong)}`, backgroundSize: `${s}px ${s}px` };
case "graph":
case "blueprint": {
const blue = pattern === "blueprint";
const minor = blue ? mix("var(--primary)", 0.14 * k) : line;
const major = blue ? mix("var(--primary)", 0.32 * k) : strong;
const big = s * 5;
return {
...base,
backgroundColor: blue ? `color-mix(in oklab, var(--primary) ${Math.round(7 * k)}%, var(--background))` : undefined,
backgroundImage: [
`linear-gradient(to right, ${major} 1px, transparent 1px)`,
`linear-gradient(to bottom, ${major} 1px, transparent 1px)`,
`linear-gradient(to right, ${minor} 1px, transparent 1px)`,
`linear-gradient(to bottom, ${minor} 1px, transparent 1px)`,
].join(", "),
backgroundSize: `${big}px ${big}px, ${big}px ${big}px, ${s}px ${s}px, ${s}px ${s}px`,
};
}
case "ruled": {
const images = [`linear-gradient(to bottom, transparent ${s - 1}px, ${strong} ${s - 1}px)`];
const sizes = [`100% ${s}px`];
const positions = [position];
if (options.margin !== false) {
images.unshift(`linear-gradient(to right, transparent ${s * 2}px, ${mix("var(--destructive)", 0.45 * k)} ${s * 2}px ${s * 2 + 1}px, transparent ${s * 2 + 1}px)`);
sizes.unshift("100% 100%");
positions.unshift("0 0");
}
return { ...base, backgroundImage: images.join(", "), backgroundSize: sizes.join(", "), backgroundPosition: positions.join(", "), backgroundRepeat: options.margin !== false ? "no-repeat, repeat" : "repeat" };
}
case "isometric": {
// One tile is a triangle side wide and two triangle heights tall; its diagonals and two rules tile into the grid.
const h = Math.round(s * Math.sqrt(3) * 100) / 100;
return {
...base,
backgroundImage: [diagonal("to top right", line), diagonal("to bottom right", line), `linear-gradient(to bottom, ${line} 1px, transparent 1px)`].join(", "),
backgroundSize: `${s}px ${h}px, ${s}px ${h}px, ${s}px ${h / 2}px`,
};
}
case "grain":
return { ...base, backgroundImage: grainUri(0.32 * k), backgroundSize: `${s}px ${s}px` };
}
}
const FADES: Record<Fade, string | undefined> = {
none: undefined,
center: "radial-gradient(ellipse 60% 60% at 50% 50%, #000 15%, transparent 100%)",
top: "linear-gradient(to bottom, #000, transparent 85%)",
bottom: "linear-gradient(to top, #000, transparent 85%)",
edges: "radial-gradient(ellipse 75% 75% at 50% 50%, #000 45%, transparent 100%)",
};
export type PaperPatternProps = PatternOptions & {
pattern: Pattern;
fade?: Fade;
as?: ElementType;
className?: string;
children?: ReactNode;
};
/** A surface with a decorative pattern layer behind its children. */
export function PaperPattern({ pattern, scale, opacity, origin = "edge", margin, fade = "none", as: Tag = "div", className, children }: PaperPatternProps) {
const mask = FADES[fade];
const layer = patternStyle(pattern, { scale, opacity, origin, margin });
return (
<Tag className={cn("relative isolate", pattern === "blueprint" && !mask && "bg-background", className)}>
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 -z-10 rounded-[inherit]"
style={{
...layer,
padding: origin === "content" ? "inherit" : undefined,
maskImage: mask,
WebkitMaskImage: mask,
}}
/>
{children}
</Tag>
);
}
