Components and layouts

Style an Astro component

Use scoped component styles by default and make global styling an explicit decision.

8 minute lesson

~~~

A normal <style> tag belongs to the component:

<article class="card">
  <slot />
</article>

<style>
  .card {
    border: 1px solid currentColor;
    padding: 1rem;
  }
</style>

Astro rewrites the selector and adds a generated scope attribute to matching markup. Another component can use .card without accidentally receiving this rule.

Scoping follows component boundaries. A parent’s scoped selector is not a reliable way to reach deep into a child component. Give the child a prop or class it deliberately supports, or move a genuinely shared rule into a global stylesheet.

Import global CSS from a layout for resets, design tokens, typography, and rules intentionally shared by the whole site. Use :global() only for a small, explicit escape from scoping; broad global selectors make components harder to reason about.

Inspect the rendered HTML and CSS once. The generated attributes explain why the rule is local and help diagnose selectors that do not reach the element you expected.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →