0
0
AstroHow-ToBeginner ยท 3 min read

How to Use Scoped Styles in Astro: Simple Guide

In Astro, you can use <style scoped> inside your component to apply CSS only to that component, preventing styles from leaking globally. This keeps your styles local and avoids conflicts with other parts of your site.
๐Ÿ“

Syntax

Use the <style scoped> tag inside your Astro component to write CSS that applies only to that component. The scoped attribute ensures styles do not affect other components or global elements.

Example parts:

  • <style scoped>: Starts a scoped style block.
  • CSS rules inside: Written normally, but only apply locally.
  • </style>: Ends the style block.
html
<style scoped>
  p {
    color: blue;
  }
</style>
๐Ÿ’ป

Example

This example shows a simple Astro component with scoped styles that color the paragraph text blue only inside this component.

astro
---
// No frontmatter needed for this example
---

<p>This text is blue because of scoped styles.</p>

<style scoped>
  p {
    color: blue;
    font-weight: bold;
  }
</style>
Output
<p style="color: blue; font-weight: bold;">This text is blue because of scoped styles.</p>
โš ๏ธ

Common Pitfalls

Common mistakes when using scoped styles in Astro include:

  • Forgetting the scoped attribute, which causes styles to apply globally.
  • Trying to style elements outside the component, which scoped styles cannot affect.
  • Using global selectors inside scoped styles expecting them to affect other components.

Always remember scoped styles only affect the current component's markup.

html
<!-- Wrong: styles apply globally without scoped -->
<style>
  p { color: red; }
</style>

<!-- Right: styles apply only inside this component -->
<style scoped>
  p { color: red; }
</style>
๐Ÿ“Š

Quick Reference

FeatureDescription