Course contentsShow
← React
Lesson 1938 of 2,39644. Styling ApproachesFree lesson

Global Styles and CSS Reset

Applying global styles with globalStyle() and understanding the scoping rules for base element styling.

Global Styles and CSS Reset

What You'll Learn: How to apply global base styles and CSS resets in vanilla-extract using the globalStyle() function while understanding its scoping rules.

Why Global Styles Matter

Even in a component-first world, you need some global styles. Browser defaults are inconsistent—margins on <body>, different heading sizes, varying button styles. A CSS reset normalizes these, giving you a clean foundation. With vanilla-extract's zero-runtime approach, you still need a way to inject these global rules without breaking type safety.

The globalStyle() Function

Vanilla-extract provides globalStyle() for this exact purpose. Unlike style() (which returns a scoped class name), globalStyle() targets base elements or global selectors directly:

// reset.css.ts
import { globalStyle } from '@vanilla-extract/css';

globalStyle('*, *::before, *::after', {
  boxSizing: 'border-box',
  margin: 0,
  padding: 0,
});

globalStyle('body', {
  fontFamily: 'system-ui, sans-serif',
  lineHeight: 1.5,
  color: '#333',
});

globalStyle('img, picture, svg', {
  display: 'block',
  maxWidth: '100%',
});

Scoping Rules: The Critical Detail

Here's the catch: globalStyle() must be defined in a .css.ts file that gets imported somewhere in your app. If you define it but never import the file, the styles won't exist. Think of it like declaring a variable in a module—it only runs when that module loads.

Import your reset file at the app root:

// main.tsx
import './reset.css.ts'; // ← Triggers global style injection
import App from './App';

Key Takeaway: Use globalStyle() in vanilla-extract to apply CSS resets and base element styling, but remember these rules only activate when you import the .css.ts file containing them—usually in your app's entry point.