A `<style>` Tag That's Scoped to the Component
Styling — First Look
An Astro component's `<style>` tag is scoped to that component by default. Write plain CSS without worrying about collisions.
What you'll learn
- Add a `<style>` block to a component
- Understand component-scoped CSS
- Recognize global styles (briefly)
A .astro file can include a <style> tag. By default it’s scoped
to that component — Astro rewrites the selectors so they only
match elements in this file.
Scoped Styles
---
// Card.astro
---
<section class="card">
<slot />
</section>
<style>
.card {
border: 1px solid #ddd;
padding: 1rem;
}
</style> The output class attribute gets a unique suffix
(class="card astro-abc123"), and the CSS becomes
.card.astro-abc123 { ... }. Another component’s .card won’t
conflict.
What That Means In Practice
- Style your components freely with simple class names
- Reuse
.title,.button,.cardacross components — they won’t clash - Inspector sees the suffixed classes, not pretty
Global Styles
When you genuinely want a global rule (CSS variables, body styles,
typography defaults), use is:global:
<style is:global>
:root {
--brand: #6360ff;
}
body {
font-family: system-ui;
}
</style> We’ll come back to scoped vs global in the components chapter.
CSS Variables From Frontmatter
Embed a frontmatter value into CSS via define:vars:
---
const accent = "tomato";
---
<button class="cta">Buy</button>
<style define:vars={{ accent }}>
.cta {
background: var(--accent);
}
</style> Astro injects --accent: tomato as an inline style and the CSS
reads it. Useful for theming based on data.
Linking a Stylesheet
For a global stylesheet outside .astro files:
---
import "../styles/global.css";
--- The CSS is included in the build.
End of Chapter
That wraps the basics. Next chapter: how files in src/pages/
become URLs.