0
0
Astroframework~5 mins

Why Astro handles styles efficiently

Choose your learning style9 modes available
Introduction

Astro loads only the styles needed for each page. This keeps websites fast and avoids extra code slowing things down.

When building a website with many pages that have different styles.
When you want your site to load quickly on slow internet connections.
When you want to avoid style conflicts between components.
When you want to keep your CSS organized and only send what is necessary.
When you want to improve user experience by reducing page load times.
Syntax
Astro
/* Astro automatically scopes styles in components */
<style>
  .button {
    background-color: blue;
    color: white;
  }
</style>

---

<button class="button">Click me</button>
Astro scopes styles to components, so styles don't leak to other parts of the site.
Styles are only included in the page if the component is used, saving bandwidth.
Examples
This style applies only to the heading in this component.
Astro
<style>
  h1 {
    color: red;
  }
</style>

<h1>Hello World</h1>
Using global makes styles apply to the whole page, not just the component.
Astro
<style global>
  body {
    margin: 0;
    font-family: sans-serif;
  }
</style>
Sample Program

This example shows a button component with its own styles. Astro includes only the button styles on the page where the button is used.

Astro
---
// Button.astro
<style>
  button {
    background-color: green;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 0.25rem;
  }
</style>

<button>Press me</button>

---
// Page.astro
---
import Button from './Button.astro';
---
<html lang="en">
  <head>
    <title>Astro Style Example</title>
  </head>
  <body>
    <h1>Welcome</h1>
    <Button />
  </body>
</html>
OutputSuccess
Important Notes

Astro's style scoping prevents styles from accidentally affecting other parts of your site.

Only styles for components used on a page are sent to the browser, improving speed.

You can use global styles when you want to apply CSS site-wide.

Summary

Astro loads styles only for components used on a page.

This keeps websites fast and avoids style conflicts.

You can choose scoped or global styles depending on your needs.