Components & styles · Lesson 6 of 22 · 15 min
Add and organize styles
Global CSS, scoped component styles, and CSS variables that keep your design consistent.
Astro gives you two places to put CSS:
- Global styles in a
.cssfile you import. They apply everywhere. - Scoped styles in a
<style>tag inside a component. They only apply to that component.
Use global for the basics (fonts, colors, resets). Use scoped for everything else.
1. Global styles with CSS variables
Create src/styles/global.css:
src/styles/global.css
:root {
--color-bg: #fffaf3;
--color-text: #1f1b16;
--color-muted: #6b6259;
--color-accent: #c2410c;
--color-card: #ffffff;
--radius: 12px;
--max-width: 960px;
--font-body: system-ui, -apple-system, "Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: var(--font-body);
line-height: 1.6;
color: var(--color-text);
background: var(--color-bg);
}
a {
color: var(--color-accent);
}
img {
max-width: 100%;
}
.container {
max-width: var(--max-width);
margin: 0 auto;
padding: 0 1.25rem;
}
The --color-* lines are CSS variables. Define them once, use them everywhere with var(--color-accent). Change one value and the whole site updates.
Import the file in the frontmatter of index.astro:
src/pages/index.astro
---
import Header from '../components/Header.astro';
import '../styles/global.css';
// ...rest of your script
---
Astro bundles and optimizes imported CSS for you.
2. Scoped styles in the Header
Add a <style> tag to the bottom of Header.astro:
src/components/Header.astro
<!-- below the </header> tag -->
<style>
header {
border-bottom: 1px solid #eadfd2;
background: var(--color-card);
}
.inner {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 1rem;
padding-top: 1rem;
padding-bottom: 1rem;
}
.logo {
font-weight: 800;
font-size: 1.25rem;
color: var(--color-text);
text-decoration: none;
}
</style>
3. Scoped styles in the Nav
src/components/Nav.astro
<!-- below the </nav> tag -->
<style>
ul {
display: flex;
gap: 1.25rem;
list-style: none;
margin: 0;
padding: 0;
}
a {
color: var(--color-text);
text-decoration: none;
font-weight: 500;
}
a:hover,
a.active {
color: var(--color-accent);
}
</style>
How scoping works
Look at the Nav’s ul and a selectors. Those would normally hit every list and link on the page. They don’t, because Astro adds a unique attribute to the component’s HTML and rewrites the CSS to match:
<ul data-astro-cid-abc123>...</ul>
ul[data-astro-cid-abc123] { display: flex; }
So you can write short, simple selectors without worrying about breaking another component. Inspect the page in dev tools to see it.
Where styles live, at a glance
| What | Where |
|---|---|
| Colors, fonts, spacing tokens | :root variables in global.css |
| Resets and base element styles | global.css |
Shared layout helpers (.container) |
global.css |
| Anything about one component | That component’s <style> |