Creating Style Objects with style()
You'll learn how to define type-safe, scoped CSS using vanilla-extract's style() function to generate unique class names at build time.
The Core Idea
Now that you've set up vanilla-extract, it's time to actually create styles. The style() function is where the magic happens—it takes a JavaScript object describing your CSS properties and returns a type-safe string representing a unique class name. Unlike styled-components or Emotion, this all happens at build time, generating real CSS files with zero runtime overhead.
Think of style() as a compiler that transforms your JavaScript style objects into optimized CSS classes—like a translator who works before your app ever runs.
How It Works
// Button.css.ts
import { style } from '@vanilla-extract/css';
export const button = style({
backgroundColor: 'blue',
color: 'white',
padding: '12px 24px',
borderRadius: '8px',
border: 'none',
cursor: 'pointer'
});
export const primaryButton = style({
backgroundColor: 'darkblue',
fontWeight: 'bold'
});
Then in your component:
// Button.tsx
import * as styles from './Button.css';
export function Button() {
return <button className={styles.button}>Click me</button>;
}
The style() function generates a unique, hashed class name like Button_button__abc123. You get full TypeScript autocomplete for CSS properties, scoping by default, and real CSS files that load normally—no JavaScript required at runtime.
Key Takeaway: style() transforms JavaScript objects into type-safe CSS class names at build time, giving you the developer experience of CSS-in-JS with the performance of static CSS files.