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
.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
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.Using Sass/SCSS
Using Sass/SCSS
Install Sass:Use in your components:
src/components/Card.astro
Importing SCSS Files
Importing SCSS Files
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.Styled Components with React
Styled Components with React
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
Prefer Scoped Styles
Use scoped styles by default for component isolation and avoiding naming conflicts.
Use CSS Variables for Theming
Define design tokens as CSS custom properties for consistent, maintainable themes.