0
0
AstroHow-ToBeginner ยท 3 min read

How to Use Global Styles in Astro: Simple Guide

In Astro, you can use global styles by importing a CSS file inside the src/layouts or src/components and adding the global attribute to the <style> tag or by importing CSS files directly in your src/pages or src/layouts. This makes the styles apply to the entire site instead of just one component.
๐Ÿ“

Syntax

To apply global styles in Astro, you can either import a CSS file globally or use the global attribute inside a <style> tag in a component or layout.

  • Import CSS file globally: Use import "./styles.css"; in your layout or root component.
  • Global style tag: Use <style global> to write CSS that affects the whole site.
astro
---
import "../styles/global.css";
---
<html>
  <head>
    <title>My Astro Site</title>
  </head>
  <body>
    <slot />
  </body>
</html>

<!-- Or inside a component -->
<style global>
  body {
    margin: 0;
    font-family: Arial, sans-serif;
  }
</style>
๐Ÿ’ป

Example

This example shows how to add a global CSS file and use a global style tag inside an Astro layout to style the entire site.

astro
---
import "../styles/global.css";
---
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Astro Global Styles Example</title>
  </head>
  <body>
    <slot />
    <style global>
      h1 {
        color: darkblue;
        text-align: center;
      }
    </style>
  </body>
</html>

/* File: src/styles/global.css */
body {
  background-color: #f0f0f0;
  margin: 0;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
Output
The entire page background is light gray, the body uses a clean sans-serif font, and all <h1> headings appear centered and dark blue.
โš ๏ธ

Common Pitfalls

Common mistakes when using global styles in Astro include:

  • Forgetting to add the global attribute on the <style> tag, which limits styles to the component only.
  • Importing CSS files inside components without placing them in a shared layout or root, causing styles to load only on some pages.
  • Using scoped styles unintentionally, which prevents styles from applying globally.
astro
<!-- Wrong: styles only apply to this component -->
<style>
  body { background: red; }
</style>

<!-- Right: styles apply globally -->
<style global>
  body { background: red; }
</style>
๐Ÿ“Š

Quick Reference

Summary tips for global styles in Astro:

  • Use import "./path/to/file.css"; in layouts or root files for global CSS.
  • Add global attribute to <style> tags for inline global CSS.
  • Place global styles in src/styles or a similar folder for organization.
  • Remember global styles affect the whole site, so keep selectors broad but specific enough to avoid conflicts.
โœ…

Key Takeaways

Import global CSS files in layouts or root components to apply site-wide styles.
Use the