Get started
Introduction
StyleX is Meta's compile-time CSS-in-JS library that generates atomic CSS and merges styles deterministically.
- StyleX documentation (stylexjs.com)
- API reference (stylexjs.com)
- GitHub repository (github.com)
Install
npm install @stylexjs/stylex
npm install -D @stylexjs/unplugin
The unplugin compiles styles and emits CSS; Babel and PostCSS work for custom pipelines.
See: Installation
Set up Vite
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import stylex from '@stylexjs/unplugin'
export default defineConfig({
plugins: [
stylex.vite({ useCSSLayers: true }),
react(),
],
})
Import one global CSS file from the root so Vite emits the generated CSS.
See: Vite setup
First style
import * as stylex from '@stylexjs/stylex'
const styles = stylex.create({
root: {
padding: 16,
color: 'rebeccapurple',
},
})
export function Card() {
return (
<div {...stylex.props(styles.root)}>
Hello
</div>
)
}
props() returns className and style to spread onto host elements.
See: Using styles
Styles
Create styles
const styles = stylex.create({
base: {
fontSize: 16,
lineHeight: 1.5,
color: 'rgb(60, 60, 60)',
},
highlighted: {
color: 'rebeccapurple',
},
})
Each key is a style object; values must be statically analyzable.
See: Defining styles
Apply styles
<div
{...stylex.props(
styles.base,
isActive && styles.highlighted,
props.style,
)}
/>
Later styles win; null, undefined, and false are ignored.
See: Using styles
Pseudo-classes
const styles = stylex.create({
button: {
backgroundColor: {
default: 'lightblue',
':hover': 'blue',
':active': 'darkblue',
},
},
})
Contextual values need a default case, even when it is null.
See: Defining styles
Pseudo-elements
const styles = stylex.create({
input: {
'::placeholder': { color: '#999' },
color: {
default: '#333',
':invalid': 'red',
},
},
})
Declare pseudo-elements as top-level keys inside a style object.
See: Defining styles
Unset styles
const styles = stylex.create({
base: {
color: null,
},
})
null removes a previous StyleX value and emits no CSS.
See: Using styles
Conditions
Media queries
const styles = stylex.create({
base: {
width: {
default: 800,
'@media (max-width: 800px)': '100%',
'@media (min-width: 1540px)': 1366,
},
},
})
@ rules live inside style values, not in separate blocks.
See: Defining styles
Combine conditions
const HOVER = '@media (hover: hover)'
const styles = stylex.create({
button: {
transform: {
default: 'scale(1)',
':hover': {
default: null,
[HOVER]: 'scale(1.1)',
},
':active': 'scale(0.9)',
},
},
})
Nest conditions to combine a media query with a pseudo-class.
See: Defining styles
Fallback values
const styles = stylex.create({
header: {
position: stylex.firstThatWorks(
'sticky', '-webkit-sticky', 'fixed'
),
},
})
The first value the browser supports wins, like stacked CSS declarations.
Contextual selectors
Styles
const HOVER =
stylex.when.ancestor(':hover')
const styles = stylex.create({
card: {
backgroundColor: {
default: 'blue',
[HOVER]: 'red',
},
},
})
Markup
const marker = stylex.defaultMarker();
<div {...stylex.props(marker)}>
<div
{...stylex.props(styles.card)}
>
Card
</div>
</div>
Mark the observed node; descendant, anySibling, and siblingAfter rely on :has().
See: stylex.when.*
Variants
Variant map
const colorVariants = stylex.create({
primary: {
backgroundColor: {
default: 'blue',
':hover': 'darkblue',
},
color: 'white',
},
secondary: {
backgroundColor: 'gray',
color: 'white',
},
});
<button
{...stylex.props(colorVariants[color])}
/>
A property lookup replaces a dedicated variant API.
See: Variants
Compound variants
const styles = stylex.create({
base: { borderWidth: 0 },
disabled: { cursor: 'not-allowed' },
})
const sizeVariants = stylex.create({
small: { fontSize: '1rem' },
medium: { fontSize: '1.2rem' },
});
<button
{...stylex.props(
styles.base,
colorVariants[color],
sizeVariants[size],
disabled && styles.disabled,
)}
/>
Extra styles merge after variants, so the last match wins.
See: Variants
Style props
import type {
StyleXStyles,
} from '@stylexjs/stylex'
type Props = {
style?: StyleXStyles
}
function Box({ style, ...props }: Props) {
return (
<div
{...props}
{...stylex.props(
styles.base,
style,
)}
/>
)
}
Accept caller styles as StyleXStyles; apply them after local styles.
See: Static types
Theming
Define variables
tokens.stylex.js
import * as stylex from '@stylexjs/stylex'
export const colors = stylex.defineVars({
accent: 'blue',
background: 'white',
line: 'gray',
})
Named exports must live in a .stylex.* file, such as .stylex.js or .stylex.ts.
See: Defining variables
Create a theme
const dark = stylex.createTheme(colors, {
accent: 'lightblue',
background: 'black',
line: 'lightgray',
});
<div {...stylex.props(dark)}>
{children}
</div>
Apply the returned style at the root of the subtree to theme it.
See: stylex.createTheme
Variables by media
const DARK =
'@media (prefers-color-scheme: dark)'
export const colors = stylex.defineVars({
background: {
default: 'white',
[DARK]: 'black',
},
accent: {
default: 'blue',
[DARK]: 'lightblue',
},
})
Variable values accept @media and @supports conditions.
See: Defining variables
Static constants
export const breakpoints =
stylex.defineConsts({
small: '@media (max-width: 600px)',
large: '@media (min-width: 1025px)',
})
Constants are inlined at build time; they emit no CSS variables.
See: stylex.defineConsts
Animation
Keyframes
const pulse = stylex.keyframes({
'0%': { transform: 'scale(1)' },
'50%': { transform: 'scale(1.1)' },
'100%': { transform: 'scale(1)' },
})
const styles = stylex.create({
pulse: {
animationName: pulse,
animationDuration: '1s',
animationIterationCount: 'infinite',
},
})
Declare keyframes in the same file where they are used.
See: stylex.keyframes
Chain animations
const fadeIn = stylex.keyframes({
from: { opacity: 0 },
to: { opacity: 1 },
})
const expand = stylex.keyframes({
from: { maxHeight: '0px' },
to: { maxHeight: '1000px' },
})
const styles = stylex.create({
open: {
animationName: `${fadeIn}, ${expand}`,
animationDuration: '1s, 1s',
},
})
Comma-separated animation values run together on one element.
See: stylex.keyframes
Dynamic values
Dynamic styles
const styles = stylex.create({
bar: (height) => ({
height,
}),
});
<div
{...stylex.props(styles.bar(height))}
/>
Function bodies must be object literals; values become CSS variables.
See: Defining styles
Inline atoms
import x from '@stylexjs/atoms'
<button
{...stylex.props(
x.display.flex,
x.gap._8px,
x.color(color),
)}
/>
Install @stylexjs/atoms to write one-off styles without a namespace.
See: @stylexjs/atoms
sx shorthand
<button sx={styles.root}>Save</button>
The compiler rewrites sx to props() on lowercase DOM elements only.
See: stylex.props
Non-React attrs
<div
{...stylex.attrs(
styles.root,
isActive && styles.active,
)}
/>
Returns class and a serialized style string for other frameworks.
See: stylex.attrs
0 Comments for this cheatsheet. Write yours!