Astro

Scoped styles

Scoped styles is the behavior of CSS rules in an .astro component's style tag that apply only to that component. Astro adds a generated attribute to match them.

How it is measured

Write a style tag in the component and use plain selectors. At build, Astro appends an attribute selector such as [data-astro-cid-abc123] to each rule and the matching attribute to the elements. Inspect an element in DevTools to see it.

Use :global() or is:global when you want a rule to reach outside. Check that a rule leaks nowhere by searching your page for the same selector in two components.

Worked example

Two components both style a class called .title. The Card uses 1.1 rem blue, and the Hero uses 3 rem black. In the built CSS they are two rules with different attributes, so neither changes the other.

A developer wants the blog's prose to style an h2 inside rendered Markdown. The scoped rule misses it because those elements have no attribute, so they use :global(h2) inside a wrapper.

How it differs

Scoped styles are a CSS behavior; an .astro component is the file that carries them. The component owns markup, props, and script. Scoping owns only the question of which elements a rule can reach, and it excludes elements in other files.

Common errors

Expecting parent scoped rules to style child component internals. Styling Markdown output without :global. Using element selectors and getting surprised by specificity. Duplicating the same rule across files. Adding global styles by accident.

In practice

Keep component styles local and put resets and typography in one global file. Use :global sparingly and inside a named wrapper. Check a component alone before placing it in a page.

See also

.astro component, Critical CSS

Sources

Count this on a real site.

Watch my website