@cssints/balance

Open in playground

import { reset } from "@cssints/reset" with { type: "cssints" };
import { cn, fontSize, fontWeight, margin, maxWidth, p } from "cssints" with { type: "cssints" };
import { balance, pretty } from "@cssints/balance" with { type: "cssints" };

reset();

// balance() evens the lines of a headline; pretty() keeps a paragraph from ending on one lonely word. Both use text-wrap where
// the browser has it and ship a small runtime where it does not.
const column = cn(maxWidth("30rem"), p(6));
const title = cn(balance(), fontSize("2rem"), fontWeight(800), margin("0"));
const lead = cn(pretty(), margin("1rem", "0", "0"));

export default function App() {
  return (
    <article className={column}>
      <h1 className={title}>A headline that breaks into lines of a similar length</h1>
      <p className={lead}>
        The paragraph below the headline avoids a last line with a single word, which is what
        pretty() asks the browser for. Resize the preview to see the lines move.
      </p>
    </article>
  );
}

text-wrap: balance and text-wrap: pretty for cssints, as members of cssints/plugin scope(). css.textWrap("balance") already gives the native feature; what this package adds is the fallback: for browserslist targets that lack text-wrap: balance (BCD css.properties.text-wrap.balance: Chrome 114, Firefox 121, Safari 17.5), a 0.55 kB script balances the lines the way nytimes/text-balancer and react-wrap-balancer do.

import { cn, fontSize } from "cssints" with { type: "cssints" };
import { balance, pretty } from "@cssints/balance" with { type: "cssints" };

export const title = cn(balance(), fontSize("2rem"));
export const lead = pretty();
@layer _.k {
  ._balance-core {
    text-wrap: balance;
  }
  ._balance-prettyCore {
    text-wrap: pretty;
  }
  /* only when a target lacks text-wrap: balance */
  @supports not (text-wrap: balance) {
    ._balance-core {
      --balance-js: 1;
    }
  }
}

Browsers

Rules

Limits

cd packages/balance && bun run test            # fixtures through the engine (kernel, fallback CSS by target, conflict)
cd packages/balance && bun run typecheck       # and the type test
cd packages/balance && bun run test:browsers   # Chrome, Firefox and WebKit through playwright-core

Credits

The idea is nytimes/text-balancer (Apache-2.0, The New York Times Company) and react-wrap-balancer (MIT, Shu Ding): find the narrowest width that keeps the line count by a binary search, and again when the parent resizes. The script is written here; no code is copied.