Trousers

Motivation

Trousers keeps a component’s styling in one place and turns it into ordinary CSS at build time. Define static style objects with css(), give optional states boolean modifiers, and give finite choices named variants. Use the React style prop for values that genuinely depend on runtime data.

Organise styles around components

This follows the useful part of BEM. A component has a base set of declarations, and modifiers describe what changes in a state or variant. A button might have a base, an independent selected modifier, and a size variant with s, m, and l choices. The emitted class names are generated, so the source can use the same vocabulary as the component’s props.

Base styles and modifiers can use simple class selectors. When declarations have equal specificity, their order in the style chain determines which one wins. This makes interactions between base styles, variants, and modifiers easier to see in the component. Pseudo-classes, nested selectors, and cascade layers still follow the browser’s normal CSS rules.

Keep rendering predictable

The bundler emits a stylesheet that the browser can cache across renders and visits. At render time Trousers selects known class names, so there is no per-render CSS serialisation or stylesheet insertion. The same classes can be rendered on the server and used during hydration. Build-time tree shaking can remove unused style declarations, while the available choices of a live variant stay in the stylesheet.

Arbitrary values can grow without a useful bound. A progress bar that generates a new CSS rule for every percentage it sees can accumulate rules as data changes. Generating and inserting those rules also adds work to updates and makes stylesheet order depend on when values appear. Keep a finite set of visual choices in modifiers or variants and pass continuous values through the style prop.

Pass runtime values through style

tsx
import { classnames, css } from 'trousers';

const fill = css({ height: 8, borderRadius: 4, backgroundColor: '#1456b7' });

export function ProgressFill({ percent }: { percent: number }) {
    return <div className={classnames(fill)} style={{ width: `${percent}%` }} />;
}

The width changes on the element while the stylesheet stays the same. Keep functions, booleans, and runtime expressions out of the style object. Use booleans to select modifiers where you apply the styles.

Styling guide · Bundlers and SSR