Getting started
brickbox turns any element into a 3D slab you can tilt, press and drag. It stays real HTML: your element is the front face, and thin walls are drawn behind it.
Install
npm i brickboxESM and CJS builds with TypeScript types are included. React is an optional peer dependency (version 17 or newer) and is only needed for brickbox/react.
Quick start
import { BrickBox } from 'brickbox/react';
export function Card() {
return (
<BrickBox depth={40}>
<div className="card">Hello, depth</div>
</BrickBox>
);
}Rules
Most problems come from breaking one of these three rules.
- The wrapper holds exactly one element, and that element is the front face.
- Layout goes on the wrapper, looks stay on the element. Flex, grid, margins and position go on the wrapper (the
BrickBoxorbrick-boxelement). Background, radius and padding stay on your child. - Opacity, filter and overflow go on the wrapper, never inside it, because they flatten the 3D.
<BrickBox style={{ margin: 24, opacity: 0.9 }}> {/* layout and opacity: wrapper */}
<div className="card">Hello, depth</div> {/* background, radius, padding: element */}
</BrickBox>What brickbox promises
- The element stays real. It’s your DOM, not a copy.
- Tiny, no dependencies.
- Quiet at rest. No timers or loops while it’s idle.
- Gentle with the page. No layout changes, walls are
aria-hidden, and reduced motion is respected. - Safe on the server. No
windowordocumentaccess while rendering. - Honest about limits. The limits are listed on the home page.
Props table
Numbers are pixels for lengths and degrees for angles. Lengths also accept CSS strings like "1.5rem". The React wrapper also takes as (default "div"), className, style and ref, which go on the outer wrapper. Use “Try it live” to open a prop in the playground.
26 props
| Prop | Values | Default | What it does |
|---|---|---|---|
| Shape and angle4 props | |||
| depthdepthTry it live ↗ | number (px) or CSS length | 24 | How far the box extends back. |
| tilttilt="14 22"Try it live ↗ | { x, y } in degrees, negatives allowed | { x: 14, y: 22 } | Resting angle. Positive x shows the bottom wall, negative x the top. Positive y shows the right wall, negative y the left. |
| maxAnglemax-angleTry it live ↗ | number (deg) | 60 | Largest angle hover and drag can reach. |
| perspectiveperspectiveTry it live ↗ | number (px) | 1000 | Camera distance. Lower looks more dramatic. |
| Motion7 props | |||
| controlcontrolTry it live ↗ | "hover", "drag", "both", "static" | "hover" | How the box reacts to the pointer. "both" tilts on hover until you grab it, drag takes over while held, then hover resumes. On touch screens "hover" and "both" behave like drag. "static" adds no tilt listeners. |
| reverseHoverreverse-hoverTry it live ↗ | boolean | false | Flip the hover tilt direction, so the box leans away from the pointer instead of toward it. |
| reverseDragreverse-dragTry it live ↗ | boolean | false | Flip the drag direction. Needs control "drag" or "both". |
| springBackspring-backTry it live ↗ | boolean | true | Return to the resting tilt after release or when the pointer leaves. |
| springDurationspring-durationTry it live ↗ | number (ms) | 700 | Length of the return animation. |
| pressSinkpress-sinkTry it live ↗ | number or string, 0 to 99 (80 or "80%") | unset (no press) | How far the face sinks when pressed, as a percent of depth. Above 99 counts as 99. Unset or 0 means no press. |
| pressDurationpress-durationTry it live ↗ | number (ms) | 150 | How fast the press happens. Only matters when pressSink is set. |
| Look6 props | |||
| sideColorside-colorTry it live ↗ | "match", "none", or any CSS colour | "match" | "match" follows the element’s background (a solid colour, or a single linear gradient continued around the edge). A colour is used exactly as given. "none" (or "transparent") builds no walls at all. |
| shadingshadingTry it live ↗ | boolean | on for "match", off for an explicit colour | Lighting on the walls. |
| lightlightTry it live ↗ | top, top-right, right, bottom-right, bottom, bottom-left, left, top-left, or degrees (0 is top, clockwise) | "top-left" | Where the light comes from. 315 is top-left. |
| shadowshadowTry it live ↗ | "none", "followLight" or "bottom", optionally followed by blur spread colour | "none" | A soft shadow of the real silhouette, holes included. "followLight" casts it away from light, "bottom" straight down. Blur and spread are in px. What you leave out comes from depth, and the distance always does. |
| edgeColoredge-colorTry it live ↗ | "none", "auto", or any CSS colour | "none" | Thin lines on the back rim and on sharp corners. "auto" is a darker line. |
| edgeWidthedge-widthTry it live ↗ | number (px) | 1 | Width of the edge lines. |
| Touch and state3 props | |||
| touchScrolltouch-scrollTry it live ↗ | boolean | true | Touch only. true lets vertical swipes scroll the page and only horizontal drags tilt. false lets both axes tilt, but a swipe starting on the box no longer scrolls the page. |
| ignoreignoreTry it live ↗ | CSS selector | none | Areas inside the element that ignore hover, drag and press, like a knob. Elements with a data-brickbox-ignore attribute are ignored too. Tick the box to add a demo knob. |
| disableddisabledTry it live ↗ | boolean | false | Render the element normally with no 3D. |
| Nesting1 prop | |||
| liftliftTry it live ↗ | number (px) or CSS length | unset | Makes this box a part standing on its parent brickbox. Its base sits lift above the parent’s face (0 sits on it), and its depth is its height. Tick the box to add a demo part. |
| Advanced5 props | |||
| advanced.tolerancetoleranceTry it live ↗ | number (px) | 0.25 | How closely curved walls follow the true curve. Lower is smoother and heavier. |
| advanced.trackColornot an attributeTry it live ↗ | boolean | true | Re-colours the walls when the face’s colour or shape changes (hover, class, theme, transitions). Turn it off to save work, and call update() yourself after a change. |
| advanced.sensitivitynot an attribute | number | 0.5 | Degrees of tilt per pixel of drag. Reference-only here. |
| advanced.bouncenot an attribute | number, 0 to 1 | 1 | 0 is a plain ease back, 1 is the springy overshoot. Reference-only here. |
| advanced.cullnot an attribute | boolean | true | Hide back-facing walls to roughly halve wall painting. Reference-only here. |
Control modes
control | What happens |
|---|---|
"hover" (default) | Tilts toward the pointer while it is over the element’s real silhouette, then springs back. On touch it behaves like "drag". |
"drag" | Grab and turn. 0.5° per pixel by default, starts after 5 px of movement, clamped to maxAngle. A drag suppresses the click that would follow it. |
"both" | Hover until you grab it, and drag takes over while held. On release, hover resumes if the pointer is still over the element, otherwise it springs back. |
"static" | No pointer tilt. The box stays at its resting tilt. |
Pointer options
maxAngleis the largest angle hover and drag can reach.springBackandspringDurationcontrol the return to the resting tilt.reverseHoverandreverseDragflip each direction on its own.touchScroll(on by default) lets vertical swipes scroll the page, so only horizontal drags tilt a"hover"box.
<BrickBox control="both" reverseDrag>
<div className="card">Grab me</div>
</BrickBox>Touch
There is no hover on touch screens, so "hover" and "both" behave like "drag". With touchScroll on, "hover" uses touch-action: pan-y. "drag" and "both" set touch-action: none.
Ignore areas
Mark part of the element with data-brickbox-ignore, or pass a selector with ignore. Over that area the tilt holds still, and a drag or press can’t start there. A drag that began elsewhere keeps going across it.
<BrickBox>
<div className="card">
<h2>Volume</h2>
<input type="range" data-brickbox-ignore />
</div>
</BrickBox>
{/* or: <BrickBox ignore=".knob, .slider"> */}Shapes and colours
Shapes
brickbox reads the shape from your element’s CSS, so you never describe it twice. Hover, drag and press follow the real silhouette, not the bounding box.
.donut {
width: 170px;
height: 170px;
clip-path: path(evenodd,
'M5 85 A80 80 0 1 0 165 85 A80 80 0 1 0 5 85 Z M55 85 A30 30 0 1 0 115 85 A30 30 0 1 0 55 85 Z');
}- Supported
clip-path:polygon(),circle(),ellipse(),inset()(withround) andpath(). Without a supportedclip-path, the shape comes fromborder-radius, including per-corner and elliptical radii. - Holes use even-odd nesting: a shape inside an odd number of others is a hole. Use
evenoddinpath(). That handles donuts, frames, a solid centre inside a hole, and separate islands. - Lengths can be plain px or %, or any CSS length expression the browser can evaluate:
calc(),min(),max(),clamp()and units such asremandvw.path()takes fixed numbers only. Not supported:url(#id)andshape(), which fall back to the rounded rectangle with a warning in development. - A set
clip-pathoverridesborder-radiusfor the walls. path()coordinates are fixed pixels from the element’s top-left corner, so give the element the same size as the path. Extra subpaths must start with an absoluteM.- A polygon with a zero-width slit (a “keyhole”) may show a seam. A nested
path()with the same winding and noevenoddis treated as a hole by the walls.
Colour matching
With sideColor="match", brickbox reads the child’s computed background when the box is built.
- A solid colour gives solid walls.
- A single linear gradient with
rgb()orrgba()stops is continued around the edge. - Anything else falls back to the element’s background colour, or to a neutral grey if that is transparent. That covers images, stacked backgrounds, radial and conic gradients, and stops in px or em.
.solid { background: #00AA3C; }
.gradient { background: linear-gradient(135deg, rgb(255, 178, 0), rgb(234, 55, 55)); }
.image { background-color: #AB54F7; background-image: url(stripes.svg); }The walls follow the face when its colour or shape changes. brickbox re-reads the face after a pointer enters, leaves, presses or releases, after focus changes, after a class or style change on the face, after a theme change on <html> (a class, an attribute or the colour scheme), and frame by frame while a colour or shape transition or a finite animation runs. Nothing runs while the box is idle. It can miss a change that reaches the face through a stylesheet edit, a class on a middle ancestor, or an infinite animation, so call box.update({}) to refresh the walls then, or turn tracking off with advanced.trackColor. Walls always follow the background, never the border colour.
Walls and edges
sideColoraccepts"match"or any CSS colour, which paints the walls exactly that colour."none"(or"transparent") builds no walls at all, which suits a box that only tilts its children.shadingandlightcontrol the lighting on the walls.edgeColorandedgeWidthdraw lines on the back rim and on sharp corners.box-shadowandoutlineare not extruded. Borders stay on the front face.
Press and shadows
Press and sink
Set pressSink to a percent of depth and the face sinks toward the back when pressed. It’s off unless you set it. 70 sinks the face most of the way, and 99 is the most it takes. A press starts on pointer down and is cancelled as soon as a drag begins.
<BrickBox depth={40} pressSink={70} pressDuration={150}>
<button className="btn">Press me</button>
</BrickBox>Shadows
<BrickBox depth={40} shadow="followLight">
<div className="card">Soft shadow</div>
</BrickBox>"followLight" casts the shadow away from light, from any direction: light from the top-left puts the shadow at the bottom-right, and light from the right puts it on the left. "bottom" always casts it straight down, and "none" (the default) turns it off.
Add blur, spread and colour after the mode, in that order, like box-shadow without the offsets: shadow="followLight 12px 2px rgba(0,0,0,.4)". Blur and spread are in px, and spread may be negative. What you leave out is chosen from depth: blur equal to depth, spread 0, colour rgba(0,0,0,.35). The distance always comes from depth too (0.6 × depth), so a deeper box casts a longer, softer shadow.
The shadow is the flat silhouette of your element, holes included, drawn behind the box. It follows the box as it tilts, hovers, drags and presses: the side that lifts away casts a longer shadow, and a pressed box casts a tighter one. An ancestor with overflow: hidden will cut it off, so leave it room.
Nesting
Give a box a lift and it becomes a part standing on its parent brickbox, in the same 3D scene, so it tilts with the parent and stands out from it.
<BrickBox depth={36} control="drag" shadow="followLight">
<div className="remote">
<BrickBox lift={0} depth={12} pressSink={65}>
<button className="key">OK</button>
</BrickBox>
<BrickBox lift={12} depth={8} pressSink={60}>
<button className="key small">GO</button>
</BrickBox>
</div>
</BrickBox>lift is how high the part’s base sits above the parent’s face (0 sits on it), and depth is the part’s height. In the example GO sits on top of OK, because its lift equals OK’s depth.
How a nested box behaves
- It is static, untilted and shaded, and it uses its parent’s
light. - Pressing it presses only it, and the parent doesn’t start a drag. Hovering over it still tilts the parent.
- Its shadow falls on the parent’s face.
- A box inside another box that has no
liftbehaves exactly as before. - It uses the browser’s own hit test, so it works inside a rotated parent.
When a part doesn’t stand out
Something between the part and its parent’s face flattens the 3D scene: overflow other than visible, opacity below 1, filter, clip-path, mask, isolation: isolate, mix-blend-mode or contain: paint. In development brickbox names the element. Remove it, or move the part out of it. A parent face with its own clip-path can’t have parts standing out of it either, so put the part next to it.
Try it in the playground with “Add a nested part”.
API
Plain JavaScript
import { brickbox } from 'brickbox';
import type { BrickBoxOptions, BrickBoxInstance } from 'brickbox';
const box: BrickBoxInstance = brickbox(wrapperEl, options);
box.update({ depth: 60 }); // merges; a key set to undefined resets to its default
box.destroy(); // removes the structure and restores the original markupAlso exported as types: Advanced, Control, LightWord, Tilt. Pass the advanced options as advanced: { ... }.
React
| Prop | Type | Default | What it does |
|---|---|---|---|
as | element type | "div" | Element type of the outer wrapper. |
className, style, ref and other HTML attributes | as usual | none | Go on the outer wrapper. Layout props belong here. |
children | exactly one React element | required | The front face. |
<BrickBox> renders the whole structure itself, so React owns the DOM, and the core attaches to it. Changing a prop calls update for you. The BrickBoxProps type is exported from brickbox/react.
Custom element
Attribute names are the kebab-case form of the options. Changing an attribute updates the box live. Call defineBrickBox() once, or defineBrickBox('my-box') for another tag name. The element needs exactly one element child.
| Attribute | Notes |
|---|---|
depth | A number, or a CSS length such as 2rem. |
control | hover, drag, both or static. |
tilt | Two numbers, written tilt="14 22" (a comma works too). |
max-angle, spring-duration, press-sink, press-duration, perspective, edge-width | Numbers. press-sink is a percent of depth, 0 to 99. |
spring-back, shading, touch-scroll, disabled, reverse-hover, reverse-drag | Booleans. Present, or any value except "false", means true. ="false" means false. |
side-color, edge-color | Any CSS colour, plus match or none for side-color and none or auto for edge-color. |
light | A word such as top-left, or a number in degrees. |
ignore | A CSS selector. |
lift | A number, or a CSS length. Nests the box on its parent brickbox. |
shadow | A mode, optionally followed by blur, spread and colour: shadow="followLight 12px 2px rgba(0,0,0,.4)". |
tolerance | Number. The only advanced option exposed as an attribute. |
Server rendering and motion
Server rendering
<BrickBox> is designed to be safe on the server: it doesn’t touch window or document while rendering. It renders your element inside the wrapper as normal, and the walls appear after the component mounts in the browser. Automated tests don’t cover server rendering yet. The plain brickbox() function and the custom element need a DOM, so call them in the browser.
Reduced motion
Hover tilt is off, and the press and spring transitions are removed.
Development warnings
When process.env.NODE_ENV isn’t "production", brickbox warns when depth is more than half of perspective and when a clip-path isn’t supported.
Troubleshooting
My box looks flat.
opacity, filter or overflow is probably on the child or the 3D layer. Move it to the wrapper.
The shape is a rounded rectangle, not my clip-path.
It probably uses url(#id) or shape(), which aren’t supported (calc(), min(), max() and clamp() are). Rewrite it as polygon(), circle(), ellipse(), inset() or path().
My nested box doesn’t stand out from its parent.
Something between the nested box and its parent’s face flattens the 3D scene: overflow other than visible, opacity below 1, filter, clip-path, mask, isolation: isolate, mix-blend-mode or contain: paint. In development brickbox names the element. Remove it, or move the nested box out of it. A parent face with its own clip-path can’t have parts standing out of it either, so put the part next to it.
The keys move away from under my pointer.
When the parent tilts on hover, everything on it moves, so a small key can slide out from under a still pointer. For a panel with many small keys, use control="drag" on the parent, or a small maxAngle.
The walls look clipped or distorted.
depth is probably more than about half of perspective. Lower the depth or raise perspective.
The page slows down with many boxes.
Every wall segment is its own element with a 3D transform. Raise advanced.tolerance for fewer, coarser segments, and use fewer boxes where you can. Boxes that share a path() share one sampling, and boxes far off screen wait to build their walls until you scroll close.
Nothing happens with <brick-box>.
Check that you called defineBrickBox(), and that the element has exactly one element child.
:active or onPointerDown on my element fires before a drag.
That’s a known limit, and it only applies when pressSink is set. A press is cancelled when a drag starts, but handlers and :active styles on your own element can fire first. Put buttons and inputs inside a data-brickbox-ignore area and brickbox won’t start a press or drag on them.
Still stuck? Open an issue and say which browser and version you used.
Migration
0.2 to 0.3: pressDepth is now pressSink
pressDepth was the depth the box shrank to while pressed. pressSink is how far it sinks, as a percent of depth. Unset means no press, so nothing sinks unless you ask. The custom element attribute changed from press-depth to press-sink. In development, passing pressDepth logs a warning. Projects that stay on 0.2.x see no change.
To convert, use (1 − pressDepth ÷ depth) × 100. A box with depth=40 and pressDepth=8 sinks 80%:
// 0.2
<BrickBox depth={40} pressDepth={8}>
// 0.3 and later
<BrickBox depth={40} pressSink={80}>0.3 to 1.0: nothing breaks
Boxes without lift are untouched. What is new: nesting with lift, sideColor: "none", advanced.trackColor, calc() and friends in a clip-path, and walls and shadows that follow the face as it changes. You can usually delete update() calls you added only to refresh colours. update({}) still works. The core grows by about 2.2 KB gzipped.
Everything that changed in each release is in the changelog below.
Changelog
1.0.0
New
- Nesting. Give a box a
liftand it becomes a part standing on its parent brickbox, in the same 3D scene, so a button can stand out from a tilting panel.liftis how high the part’s base sits above the parent’s face (0 sits on it), anddepthis the part’s height. A nested box is static, untilted and shaded by default, and it uses its parent’slight. It uses the browser’s own hit test, so it works inside a rotated parent. Pressing it presses only it and the parent does not start a drag, while hovering over it still tilts the parent. Its shadow falls on the parent’s face. A box withoutliftis untouched, so nothing changes for existing pages. In development, brickbox names any element between the part and its parent that flattens the 3D scene (overflow,opacity,filter,clip-path,mask,isolation,mix-blend-mode,contain: paint). sideColor: "none"(or"transparent") builds no walls at all, which suits a box that only tilts its children.advanced.trackColor(default on) turns the colour and shape tracking below off.
Changed
- The walls follow the face as its colour or shape changes, with no call to
update(). brickbox re-reads the face after pointer, focus, class, style and theme changes, and frame by frame only while a colour or shape transition or a finite animation runs. Nothing runs while the box is idle. A colour-only change repaints the existing wall strips without rebuilding them.update({})still refreshes the walls. - The shadow follows the box as it tilts, hovers, drags and presses. It is now the box’s face projected along the light onto a plane behind it, in the same 3D scene, so it gets the same perspective. A pressed box casts a tighter shadow.
clip-pathacceptscalc(),min(),max(),clamp()and units such asremandvwinpolygon(),inset(),circle()andellipse(). The browser evaluates them.url()andshape()are still not supported.- The depth warning in development is shown once.
- The core grows by about 2.2 KB gzipped.
0.3.0
Breaking
pressDepthis replaced bypressSink: how far the box sinks when pressed, as a percent ofdepth. It takes a number or a string such as"80%", from 0 to 99 (anything higher counts as 99). Unset means no press, so nothing sinks unless you ask. The custom element attribute is nowpress-sink, andpress-depthis gone. Projects that stay on 0.2.x keeppressDepthand see no change. In development, passingpressDepthlogs a warning that points here.
New
shadow: a soft shadow of the box’s real silhouette, holes included."followLight"casts it away fromlightin any direction,"bottom"casts it straight down, and"none"(the default) turns it off. Addblur spread colorafter the mode, likebox-shadowwithout the offsets, for example"followLight 12px 2px rgba(0,0,0,.4)". What you leave out is chosen fromdepth, and the distance always comes fromdepth.
Fixed
- Dragging in
dragandbothmode no longer selects text or scrolls the page along with the selection. Text selection is switched off only while a drag is in progress, and never when you press on an input, textarea, select or editable element.
Faster (measured in headless Chromium)
path()sampling is adaptive and cached. It takes about a half to a third of the samples, and many boxes that share one path sample it once. Thirty identical donuts took about 2.6 s to build in 0.2.0 and about 0.03 s now. A single donut went from about 90 ms to about 45 ms.- A rebuild that changes nothing visible is skipped.
update({}), adepthchange and the second build at startup now do almost no work.update({})still re-reads the face colour, so it stays the way to refresh the walls after a colour change. - A box more than about 300 px outside the viewport waits to build its walls until it scrolls close.
- The core grows by about 1.7 KB gzipped.
0.2.0
Changes
- Any shape: walls follow
clip-path(polygon(),circle(),ellipse(),inset(),path()) and ellipticalborder-radius. Hover and drag follow the real silhouette. control: "both": hover tilts until you grab it, drag takes over while held, then hover resumes.reverseHoverandreverseDragswitch the direction of each independently.ignoreoption anddata-brickbox-ignoreattribute: areas that do not trigger hover, drag or press.- Walls follow only the visible part of a clip-path, so a path that spills past the element’s box no longer leaves round walls under a flat face.
- The core grows by about 2 KB gzipped.
0.1.0
First public release
- Framework-free core:
brickbox(el, options). - React wrapper:
brickbox/react. - Custom element:
brickbox/element(<brick-box>). - Strip-based side walls that follow rounded corners and continue gradient backgrounds.
- Hover, drag and static control; press-to-sink; optional edge lines.
The full history is also in the CHANGELOG on GitHub.