How to Add CSS in Astro: Simple Methods Explained
In Astro, you can add CSS by using
<style> tags inside your component for scoped styles, importing external CSS files with import './styles.css';, or adding global styles with global attribute in the <style> tag. These methods let you style your components easily and keep styles organized.Syntax
Astro supports CSS in three main ways:
- Scoped styles: Use a
<style>tag inside your Astro component. Styles apply only to that component. - Global styles: Add
globalattribute to the<style>tag to apply styles globally. - External CSS: Import CSS files directly in your component script.
astro
<!-- Scoped CSS inside Astro component -->
<style>
h1 {
color: blue;
}
</style>
<!-- Global CSS inside Astro component -->
<style global>
body {
margin: 0;
font-family: Arial, sans-serif;
}
</style>
---
---
<!-- Import external CSS file -->
---
import './styles.css';
---Example
This example shows an Astro component with scoped CSS, global CSS, and an imported external CSS file. The scoped style colors the heading blue, the global style sets body margin and font, and the external CSS adds a red background to a div.
astro
--- import './external.css'; --- <style global> body { margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } </style> <style> h1 { color: blue; } </style> <h1>Hello from Astro</h1> <div class="box">This box has red background from external CSS</div>
Output
<h1 style="color: blue;">Hello from Astro</h1>
<div class="box" style="background-color: red; padding: 1rem; color: white;">This box has red background from external CSS</div>
Common Pitfalls
Common mistakes when adding CSS in Astro include:
- Forgetting the
globalattribute on<style>when you want styles to apply globally. - Not importing external CSS files properly with
import './file.css';. - Expecting scoped styles to affect child components or global elements.
- Using inline styles without considering maintainability.
astro
<!-- Wrong: scoped style won't affect body globally -->
<style>
body {
margin: 0;
}
</style>
<!-- Right: add global attribute -->
<style global>
body {
margin: 0;
}
</style>Quick Reference
Summary of CSS methods in Astro:
| Method | Usage | Scope |
|---|---|---|
| Scoped CSS | Only inside current component | |
| Global CSS | Applies to whole site | |
| External CSS | import './file.css'; | Depends on CSS selectors, global by default |
Key Takeaways
Use