# Styling

Write StyleX styles with arene's tokens, overrides and shared states.

Write your app's styles with `stylex.create()`. Use arene's tokens for design
values and pass styles to components through `xstyle`.

## Override props

`xstyle` takes StyleX styles. Each component merges it last, so your declarations
win over its own. It can take an array of styles, including conditional entries.

`className` is a hook for plain CSS. Components concatenate it without resolving
conflicts. Use `xstyle` when a declaration must override the component's style.

`style` is ordinary inline CSS. Use it for values you only know at runtime,
such as a measured width. Keep design values in compiled styles.

## Tokens

Import tokens from `theme/tokens.stylex.ts`. The groups have different jobs:

| Group      | Use                                                                           |
| ---------- | ----------------------------------------------------------------------------- |
| `color`    | Semantic colors and control materials, with light and dark values.            |
| `interop`  | Flat custom properties for CSS, including the reset's border and ring colors. |
| `space`    | Gaps, padding and control dimensions.                                         |
| `width`    | Named content widths.                                                         |
| `radius`   | Corner radii.                                                                 |
| `shadow`   | Focus rings, control shadows and raised surfaces.                             |
| `font`     | Sans and mono font stacks.                                                    |
| `text`     | Font sizes.                                                                   |
| `leading`  | The line height paired with each font size.                                   |
| `tracking` | Letter spacing.                                                               |
| `duration` | Transition durations.                                                         |
| `ease`     | Transition timing functions.                                                  |
| `layer`    | Stacking levels for raised, overlay, sticky and popup elements.               |

Always write `fontSize` and `lineHeight` together. `text.sm` is only a size.
Without `leading.sm`, it inherits the ancestor's line height and changes the
spacing of the type scale. The leading tokens are unitless ratios, so their
line boxes scale with the font size.

```ts
import * as stylex from "@stylexjs/stylex"
import { leading, text } from "@/theme/tokens.stylex"

const styles = stylex.create({
  caption: { fontSize: text.sm, lineHeight: leading.sm },
})
```

## Keep entries whole

A shared style replaces a whole entry or carries shared behaviour. Do not turn
each CSS property into a named style and assemble a component from those names.
A reader should see what an entry does without following a list of fragments.

This fragments a caption into utilities:

```ts
const styles = stylex.create({
  small: { fontSize: text.sm, lineHeight: leading.sm },
  muted: { color: color.mutedForeground },
  narrow: { maxWidth: width.sm },
})

const sx = stylex.props(styles.small, styles.muted, styles.narrow)
```

Keep the caption together instead:

```ts
const styles = stylex.create({
  caption: {
    fontSize: text.sm,
    lineHeight: leading.sm,
    color: color.mutedForeground,
    maxWidth: width.sm,
  },
})

const sx = stylex.props(styles.caption)
```

Both versions use `text`, `leading`, `color` and `width` from
`theme/tokens.stylex.ts`. Repeating a token in two cohesive entries is fine.
Extract a style when the entries have the same job, or when they share behaviour
such as a focus ring. StyleX deduplicates atomic declarations in the output;
you do not need a utility for each declaration to reduce CSS.

## Merge once per element

Pass every style for an element to one `stylex.props()` call. Later styles win
for properties they define, including all conditions on that property.
Concatenating the classes from two calls leaves competing atomic declarations
in the element's class list. Stylesheet order then decides which wins.

```ts
const sx = stylex.props(styles.caption, selected && styles.selected)
```

Spread the complete result onto your element. It can include `style` as well
as `className`, because dynamic StyleX styles use inline variables. If you add
a plain CSS hook, combine it with `sx.className` and keep `sx.style`. A separate
`className` attribute beside the spread overwrites the spread's class.

## Reuse exported styles

Components export style maps for use on other elements. `buttonStyles` has
`base`, `variants` and `sizes`; `textStyles` has `sizes`, `tones` and `weights`.
On your own element, merge the exported styles in that element's
`stylex.props()` call. A style map supplies appearance, not keyboard behaviour
or semantics.

```tsx
import * as stylex from "@stylexjs/stylex"
import { clsx } from "clsx"
import { buttonStyles } from "@/components/ui/button"
import { ArrowSquareOutIcon } from "@phosphor-icons/react/dist/csr/ArrowSquareOut"

const sx = stylex.props(
  buttonStyles.base,
  buttonStyles.variants.outline,
  buttonStyles.sizes.default,
  buttonStyles.iconEnd.default,
)

export default function ButtonAsLink() {
  return (
    <a
      href="https://base-ui.com"
      target="_blank"
      rel="noopener noreferrer"
      data-variant="outline"
      {...sx}
      className={clsx("arene-icons", sx.className)}
    >
      Base UI
      <ArrowSquareOutIcon aria-hidden="true" />
    </a>
  )
}
```

On a arene component, pass a style through `xstyle` so the receiving component
merges it correctly. This applies one whole tone entry:

```tsx
import { Stack } from "@/components/ui/stack"
import { textStyles } from "@/components/ui/text"

;<Stack xstyle={textStyles.tones.muted}>Updated today</Stack>
```

## Breakpoints

Import `breakpoints` from `theme/breakpoints.stylex.ts`. A media query is a key
inside a property's value. Write `default` alongside the breakpoint so the
property has a value on both sides. The scale is `sm` at 40rem, `md` at 48rem,
`lg` at 64rem and `xl` at 80rem, with `maxSm` through `maxXl` for below each one.

The [Layout guide](https://www.arene.style/docs/layout#responsive-direction) shows this on a Stack.

## Shared states

Import `states` from `theme/states.ts` for shared behaviour and materials.
It includes focus and invalid rings, disabled dimming, row highlights, popup
surfaces, field surfaces, keys and wells. It also provides `srOnly`, popup
positioning and transition states. `transparent` sets opacity to zero;
`popupTransparent` also scales down. `popupSlide` maps popup sides to slide
styles. `instant` sets the transition duration to zero.

Merge a state only when it applies. `states.disabled` changes appearance and
pointer events; it does not set the native `disabled` attribute. On Base UI
parts, use their state callbacks. The `stateStyles` helper from
`lib/state-styles.ts` returns both callbacks, preserving the inline variables
from `stylex.props()`.

For your own control, merge its entry before `states.focusRing` so the shared
state owns the border color and focus shadow, including their focus conditions.
It reads `--arene-border-color` for the resting border. Set that variable in
the control entry instead of a flat `borderColor`, which would replace the
focus condition if merged after the state. These two entries do not compete
for properties, so reversing them currently gives the same result.

```tsx
import * as stylex from "@stylexjs/stylex"
import { states } from "@/theme/states"
import { color, duration, leading, radius, space, text } from "@/theme/tokens.stylex"

const styles = stylex.create({
  control: {
    "--arene-border-color": color.border,
    borderWidth: 1,
    borderStyle: "solid",
    borderRadius: radius.lg,
    paddingBlock: space.s1,
    paddingInline: space.s3,
    fontSize: text.sm,
    lineHeight: leading.sm,
    transitionProperty: "border-color, box-shadow",
    transitionDuration: {
      default: duration.color,
      "@media (prefers-reduced-motion: reduce)": "0s",
    },
  },
})

export default function StylingControl() {
  return (
    <button type="button" {...stylex.props(styles.control, states.focusRing)}>
      Focus me
    </button>
  )
}
```

### Ancestor state

For state your component knows, merge a conditional style. For an ancestor's
state, use `stylex.when.ancestor()` with a marker. Declare your own marker in a
`.stylex.ts` file, which is required for the compiler to recognize it:

```ts title="theme/markers.stylex.ts"
export const card = stylex.defineMarker()
```

Import `stylex` from `@stylexjs/stylex` in that file. Add the marker to the
ancestor's `stylex.props()` call, then use it in the child's property value:

```ts
color: {
  default: color.mutedForeground,
  [stylex.when.ancestor(":hover", card)]: color.foreground,
},
```

Use context when children need an ancestor's data, such as orientation, rather
than a CSS state. Keep selectors for DOM you do not render in plain CSS.

## Focus, motion and color schemes

Keep keyboard focus visible. Reuse `states.focusRing` or `states.rowFocusRing`
when you style a control. Do not remove the outline without a replacement.

Name the properties you transition. For motion, put
`"@media (prefers-reduced-motion: reduce)": "0s"` inside `transitionDuration`.
The control example above does this for color changes. Progress indicators
that must communicate activity can keep an opacity pulse under reduced motion.

Color tokens already use `light-dark()`. Read the same token in either scheme;
you do not need a dark selector. See [Theming](https://www.arene.style/docs/theming#dark-mode) for the
scheme switch and local themes.

## Lint and build checks

The component registry does not install these checks. Add them to your app
alongside the compiler so mistakes in your own styles fail before release.

### Lint styles

Install oxlint and the StyleX ESLint plugin. Oxlint's JavaScript plugins require
Node 22.18 or newer.

```bash
npm install -D oxlint @stylexjs/eslint-plugin
```

Copy the lint plugin to `scripts/stylex-lint.mjs` at your project root. It
rejects a `fontSize` without `lineHeight` in the same StyleX style object.

```js title="scripts/stylex-lint.mjs"
const keyName = (property) =>
  property.computed ? undefined : (property.key?.name ?? property.key?.value)

const plugin = {
  meta: { name: "arene" },
  rules: {
    "font-size-leading": {
      meta: {
        type: "problem",
        schema: [],
        messages: { missing: "Pair fontSize with lineHeight in the same style object." },
      },
      create(context) {
        const namespaces = new Set()
        const creates = new Set()
        return {
          ImportDeclaration(node) {
            if (node.source.value !== "@stylexjs/stylex") return
            for (const specifier of node.specifiers) {
              if (
                specifier.type === "ImportNamespaceSpecifier" ||
                specifier.type === "ImportDefaultSpecifier"
              )
                namespaces.add(specifier.local.name)
              if (specifier.imported?.name === "create") creates.add(specifier.local.name)
            }
          },
          ObjectExpression(node) {
            const fontSize = node.properties.find((property) => keyName(property) === "fontSize")
            if (!fontSize || node.properties.some((property) => keyName(property) === "lineHeight"))
              return
            let ancestor = node.parent
            while (ancestor) {
              if (ancestor.type === "CallExpression") {
                const callee = ancestor.callee
                if (
                  (callee.type === "MemberExpression" &&
                    namespaces.has(callee.object.name) &&
                    callee.property.name === "create") ||
                  (callee.type === "Identifier" && creates.has(callee.name))
                ) {
                  context.report({ node: fontSize, messageId: "missing" })
                  return
                }
              }
              ancestor = ancestor.parent
            }
          },
        }
      },
    },
  },
}

export default plugin
```

Copy this config to the root, or merge its `jsPlugins` and `rules` into your
existing oxlint config. These are the rules arene runs: `valid-styles` checks
style values, `no-unused` checks unused styles, `valid-shorthands` rejects
unsupported shorthands, and `enforce-extension` checks token module filenames.

```json title=".oxlintrc.json"
{
  "plugins": ["react", "typescript", "jsx-a11y"],
  "jsPlugins": [
    {
      "name": "stylex",
      "specifier": "@stylexjs/eslint-plugin"
    },
    {
      "name": "arene",
      "specifier": "./scripts/stylex-lint.mjs"
    }
  ],
  "categories": {
    "correctness": "warn"
  },
  "rules": {
    "stylex/valid-styles": "error",
    "stylex/no-unused": "error",
    "stylex/valid-shorthands": "error",
    "stylex/enforce-extension": "error",
    "arene/font-size-leading": "error"
  }
}

```

```bash
npx oxlint
```

### Check compiled tokens

Copy this Vite plugin to `plugins/stylex-token-check.ts` at your project root.
It checks all emitted CSS together and rejects hashed StyleX variables without
a definition. It runs at build time, not in dev, and does not check arbitrary
custom properties or whether a token has the intended value.

```ts title="plugins/stylex-token-check.ts"
import type { Plugin } from "vite"

export function assertResolvedTokens(css: string) {
  const defined = new Set([...css.matchAll(/(--[\w-]+)\s*:/g)].map((match) => match[1]))
  const unresolved = new Set(
    [...css.matchAll(/var\(\s*(--x[a-z0-9]+)\s*[,)]/g)]
      .map((match) => match[1])
      .filter((name) => !defined.has(name)),
  )
  if (unresolved.size > 0) {
    throw new Error(`Unresolved StyleX tokens: ${[...unresolved].join(", ")}`)
  }
}

export function stylexTokenCheck(): Plugin {
  return {
    name: "arene:stylex-token-check",
    enforce: "post",
    generateBundle(_, bundle) {
      const css = Object.values(bundle)
        .filter((entry) => entry.type === "asset" && entry.fileName.endsWith(".css"))
        .map((entry) => (entry.type === "asset" ? String(entry.source) : ""))
        .join("\n")
      assertResolvedTokens(css)
    },
  }
}
```

Add it after your StyleX and React plugins in `vite.config.ts`:

```ts
import { stylexTokenCheck } from "./plugins/stylex-token-check"

// In defineConfig:
plugins: [stylex({ /* Keep the options from Installation. */ }), react(), stylexTokenCheck()],
```

A missing compiler alias throws during compilation. An alias pointing at the
wrong existing file can instead leave an undefined hashed `var()` in the CSS.
This check catches that second case. Keep the alias and browser targets from
[Installation](https://www.arene.style/docs/installation#setup), then run your production build.
