Trousers

Styling

Define styles with css(). An optional name makes generated classes easier to recognise in devtools.

Apply styles through the JSX css prop, the classnames helper, or styled.

Boolean modifiers

tsx
const button = css('button', { color: '#243141' })
    .modifier('primary', { backgroundColor: '#f95b5b' });

<button css={button} $primary={isPrimary}>Save</button>

A modifier is off until its flag is true. A bare $primary is shorthand for $primary={true}. When rules have equal specificity, later declarations in the style chain take precedence.

Named variants

A variant selects one choice. For a box with optional inner spacing, make inset the variant and pass it through.

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

const box = css({ minHeight: 20 }).variant('inset', {
    s: { padding: 4 },
    m: { padding: 8 },
    l: { padding: 16 },
});

const Box = styled.div(box);

<Box $inset={inset} style={{ width }}>Content</Box>
<div css={box} $inset={inset}>Content</div>
<div className={classnames(box, { inset })}>Content</div>

Omit inset for the base styles. styled and classnames infer the choices 's' | 'm' | 'l'. With regular elements using the Trousers JSX runtime, $ props accept string choices and boolean flags.

Using className

Use classnames with standard React JSX or another renderer. Keep the bundler adapter configured and include its stylesheet. Pass keys without the $ prefix.

tsx
<button className={classnames(button, { primary: isPrimary })}>Save</button>

Selectors and responsive styles

A leading pseudo-selector attaches to the current selector. Use & to position that selector explicitly or a plain selector to address descendants.

tsx
const link = css({
    color: 'var(--color-accent)',
    ':hover': { textDecoration: 'underline' },
    '& > svg': { marginInlineStart: 4 },
    '@media (min-width: 768px)': { fontSize: 18 },
});

const panel = css({ containerType: 'inline-size' });
const cards = css({
    display: ['block', 'grid'],
    gap: 12,
    '@container (min-width: 360px)': {
        gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
    },
});

<section className={classnames(panel)}>
    <div className={classnames(cards)}>{children}</div>
</section>

The array emits repeated declarations in order so the browser can use the last value it supports. The container query responds to the section’s width. Numeric lengths use pixels for nonzero values on properties that take a length. Use a string for other units.

Scope a theme to part of the app

Apply a theme class to an ancestor and read the resulting CSS variables in its descendants. A nested theme can override the same variables for its own subtree.

tsx
const light = css({}).theme({ color: { surface: '#f4f8fd', text: '#243141' } });
const dark = css({}).theme({ color: { surface: '#243141', text: '#f4f8fd' } });
const card = css({
    backgroundColor: 'var(--color-surface)',
    color: 'var(--color-text)',
    padding: 12,
});

<div className={classnames(light)}>
    <p className={classnames(card)}>Light card</p>
    <aside className={classnames(dark)}>
        <p className={classnames(card)}>Dark card</p>
    </aside>
</div>

Add global rules once

Import a reset module from the application entry. .global() emits unscoped selectors, so the reset needs no class name in the markup.

ts
// reset.ts
import { css } from 'trousers';

css({}).global({
    '*, *::before, *::after': { boxSizing: 'border-box' },
    body: { margin: 0 },
});

Respect reduced motion

Declare keyframes with the component styles. Give the animation a distinct name because CSS keyframe names are shared across the stylesheet.

ts
const toast = css({
    '@media (prefers-reduced-motion: no-preference)': {
        animation: 'toast-appear 180ms ease-out',
    },
    '@keyframes toast-appear': {
        from: { opacity: 0, transform: 'translateY(4px)' },
        to: { opacity: 1, transform: 'translateY(0)' },
    },
});

Feed runtime data into static rules

Use style for a dynamic value. A CSS custom property lets an extracted declaration use that value, even when the rule targets a pseudo-element.

tsx
import type { CSSProperties } from 'react';
import { classnames, css } from 'trousers';

const progress = css({
    '&::before': {
        content: '""',
        display: 'block',
        width: 'var(--progress, 0%)',
        height: 8,
        backgroundColor: '#1456b7',
    },
});

type ProgressStyle = CSSProperties & { '--progress': string };

export function Progress({ percent }: { percent: number }) {
    const style: ProgressStyle = { '--progress': `${percent}%` };
    return (
        <div
            className={classnames(progress)}
            style={style}
            role="progressbar"
            aria-label="Completion"
            aria-valuenow={percent}
        />
    );
}

See the generated API reference for signatures and types.