Skip to main content

Overview

Astro provides multiple approaches to styling your components and pages. Choose the method that best fits your project needs and team preferences.

Scoped Styles

Astro components support scoped CSS out of the box. Styles defined in a <style> tag are automatically scoped to that component.

Basic Scoped Styles

src/components/Button.astro
The .primary class is scoped to this component and won’t affect other components with the same class name.

How Scoping Works

Astro adds unique data attributes to your elements and styles:

Global Styles

Use global styles for site-wide CSS like resets, typography, and design tokens.

Creating Global Styles

1

Create a global CSS file

src/styles/global.css
2

Import in a layout or component

src/components/BaseHead.astro

Global Modifier

Use :global() to create unscoped styles within a scoped style block:
src/layouts/BlogPost.astro

CSS Variables

Define CSS custom properties for consistent theming:
src/layouts/Layout.astro

CSS Preprocessors

Astro supports CSS preprocessors like Sass and Less out of the box.
Install Sass:
Use in your components:
src/components/Card.astro
src/styles/components.scss

Tailwind CSS

Tailwind CSS is a popular utility-first CSS framework that works seamlessly with Astro.

Installation

Configuration

astro.config.mjs

Usage

src/components/Hero.astro

CSS Modules

CSS Modules provide scoped styles with explicit imports.
src/components/Card.module.css
src/components/Card.astro

Styled Components (CSS-in-JS)

Use CSS-in-JS libraries with framework components.
src/components/StyledButton.tsx
src/pages/index.astro

PostCSS

Astro includes PostCSS support for autoprefixing and other transformations.
postcss.config.cjs

Styling Strategies

Component-First

Use scoped styles for component-specific styling. Best for isolated, reusable components.

Utility-First

Use Tailwind CSS for rapid development with utility classes. Best for prototyping and consistent design systems.

Semantic CSS

Use global CSS or preprocessors for traditional semantic class names. Best for content-heavy sites.

Hybrid Approach

Combine multiple methods: global styles for resets, scoped styles for components, and utilities for layout.

Advanced Patterns

Conditional Styles

src/components/Alert.astro

Media Queries

src/components/Grid.astro

Font Loading

src/components/BaseHead.astro

Best Practices

1

Prefer Scoped Styles

Use scoped styles by default for component isolation and avoiding naming conflicts.
2

Use CSS Variables for Theming

Define design tokens as CSS custom properties for consistent, maintainable themes.
3

Minimize Global Styles

Keep global CSS limited to resets, typography, and truly global styles.
4

Optimize for Performance

Preload critical fonts, use font-display: swap, and minimize unused CSS.