fitbox

Reflow-free text-to-box fitting for React. Built on @chenglou/pretext.

Why

Libraries like Fitty fit text to a container by measuring the DOM — put the text in, read getBoundingClientRect, adjust, repeat. Every read forces the browser to reflow the page. Twenty headings on a resizing window means thousands of reflows per second.

Pretext measures text through canvas.measureText, which doesn't reflow. With per-glyph widths cached, measuring a wrapped paragraph is microseconds of arithmetic.

When measurement stops touching layout, the algorithm collapses. Single-line fit becomes a closed form (fontSize = width / naturalWidth). Multi-line fit becomes a binary search over pure arithmetic. Responsive fit becomes a static clamp() CSS string — zero JavaScript at runtime. And because nothing depends on the DOM, the fit works equally well in SSR, in Canvas, in WebGL, in SVG.

Demos

Single-line fit

Drag the right edge to resize. Click the text to edit it — fitbox refits on every keystroke via MutationObserver.

Hello World

<h1 ref={useFit({ maxSize: 200 })} contentEditable>
  Hello World
</h1>

Multi-line fit

maxLines: 3. Click to edit — wrap points, line count, and fontSize all reflow. Still pure arithmetic, no DOM measurement.

Typography that actually fits its container, without layout thrashing or binary searches over the DOM.

<p ref={useFit({ maxLines: 3, maxSize: 48 })} contentEditable>
  {text}
</p>

Fluid CSS clamp — zero JS at runtime

Loading…

Beyond the DOM — WebGL

Loading…

Install

bun add @darkroomengineering/fitbox

Pretext ships as a dependency; no peer-install friction. For SSR, add @napi-rs/canvas and call configureServerCanvas() once at startup. Full API reference on GitHub.