0
0
AstroHow-ToBeginner ยท 3 min read

How to Use is:global in Astro for Global CSS Styling

In Astro, use is:global inside a <style> block to write CSS rules that apply globally instead of being scoped to the component. Wrap selectors with :global() or add is:global attribute to the <style> tag to make styles global.
๐Ÿ“

Syntax

The is:global directive in Astro is used inside a <style> tag to make CSS rules global rather than scoped to the component. You can use it in two ways:

  • Add is:global attribute to the entire <style> tag to make all styles inside global.
  • Use the :global() pseudo-class around specific selectors inside a scoped style block.

This lets you control whether styles affect only the component or the whole page.

astro
<style is:global>
  body {
    background-color: lightblue;
  }
</style>

<style>
  :global(h1) {
    color: red;
  }
  p {
    color: green;
  }
</style>
๐Ÿ’ป

Example

This example shows how to use is:global to style the entire page's body and globally style h1 tags, while keeping p tags styled only inside the component.

astro
---
---
<html lang="en">
  <head>
    <style is:global>
      body {
        background-color: #f0f8ff;
        font-family: Arial, sans-serif;
      }
    </style>
    <style>
      :global(h1) {
        color: darkblue;
      }
      p {
        color: darkgreen;
      }
    </style>
  </head>
  <body>
    <h1>Global Heading</h1>
    <p>This paragraph is styled only inside this component.</p>
  </body>
</html>
Output
<body style="background-color: #f0f8ff; font-family: Arial, sans-serif;"><h1 style="color: darkblue;">Global Heading</h1> <p style="color: darkgreen;">This paragraph is styled only inside this component.</p></body>
โš ๏ธ

Common Pitfalls

Common mistakes when using is:global include:

  • Forgetting to wrap selectors with :global() inside scoped styles, so styles don't apply globally.
  • Using is:global on the <style> tag but expecting scoped styles inside it.
  • Overusing global styles, which can cause unexpected style conflicts across components.

Always decide if styles should be scoped or global and use is:global accordingly.

astro
<style>
  /* Wrong: This styles only inside component, not global */
  h1 {
    color: red;
  }
</style>

<style>
  /* Right: Use :global() to style globally */
  :global(h1) {
    color: red;
  }
</style>
๐Ÿ“Š

Quick Reference

UsageDescriptionExample
:global(selector)Makes specific selector global inside scoped styles
Scoped stylesStyles apply only inside component
โœ…

Key Takeaways

Use is:global on the <style> tag to make all styles global.
Wrap selectors with :global() inside scoped styles to target global elements selectively.
Scoped styles without is:global or :global() apply only inside the component.
Avoid overusing global styles to prevent style conflicts across components.
Remember that is:global affects CSS scoping behavior in Astro components.