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
scopedattribute, 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
| Feature | Description |
|---|---|
| Defines CSS local to the component | |
| Without scoped | CSS applies globally to all matching elements |
| Scoped styles | Prevent style conflicts between components |
| Use case | Styling component-specific markup only |
Key Takeaways
Use