# Scoped styles: CSS that stays put

- Published: 2026-11-30
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-11-scoped-styles-css-that-stays-put/

> Part 11 of a series on Svelte in 2026. [Part 10](/writing/why-svelte-10-built-in-transitions-and-animations/) covered transitions and animations. This part is about the `<style>` block: what the compiler does to it, where it stops, and how to get out of it on purpose.

I had a card component that renders a child, and I wanted the child red. So I passed it a class and styled that class in the card:

```svelte title="Card.svelte"
<script>
  import Child from "./Child.svelte";
</script>

<div class="card">
  <p>own paragraph</p>
  <Child class="fancy" />
</div>

<style>
  .fancy {
    color: red;
  }
</style>
```

The child puts `props.class` on its `<p>`, and the rendered HTML said `class="child fancy"`. The text wasn't red. Svelte 5.57.2 printed a warning, and the CSS it emitted had my rule in a comment:

```css
/* (unused) .fancy {
    color: red;
  }*/
```

The warning is `css_unused_selector`: `Unused CSS selector ".fancy"`. From the compiler's side, it's correct, and the reason is the whole design of scoped styles.

## Only what the compiler sees

The docs describe the mechanism in one line: scoping "works by adding a class to affected elements."[^scoped] The compiler reads your `<style>`, matches each selector against the markup in the same file, and adds a class like `svelte-lv9s7p` to every element that could match.

Then it rewrites the selector to require that class. The card's `p` rule came out as `p.svelte-lv9s7p`, and the card's rendered `<p>` carried `class="svelte-lv9s7p"`.

So `.fancy` matched nothing. The card's markup has no element with that class; it has a `<Child>`, and a component tag isn't an element.

Whatever `Child` renders lives in another file with another hash. With nothing to attach the class to, the compiler drops the rule rather than ship CSS that can't apply.

Here's where three paragraphs landed with a global `p { color: blue }` on the page:

- The card's own `<p>` was purple, from the scoped rule.
- The child's `<p>` was blue. The card's `p` rule never reached it.
- A `<p>` from `{@html}` was blue too. The compiler can't see inside a string.

A click handler that appends an `<li>` with `document.createElement` hits the same wall. The `<li>` Svelte rendered was teal from the component's `li` rule; the appended one was black, with an empty `className`.

Anything that wasn't in the template at compile time doesn't get the class.

The compiler errs toward keeping rules when it can't tell. `<span class={active ? "on" : "off"}>` kept the `.on` rule. `<span class={cls}>`, where `cls` is a prop it knows nothing about, kept `.whatever`, a class that appears nowhere in the file.

It still dropped `i` (no `<i>` anywhere) and `b + .anything`, because the only `<b>` comes after the span. Selectors that obviously can't match get removed even next to dynamic classes.

**Quiz:** A component renders <ul>{@html itemsHtml}</ul> and styles li { padding: 4px } in its <style> block. The ul has no other children. What happens?

- The li elements from the HTML string get the padding
- The rule is commented out and you get css_unused_selector
- Every li on the page gets the padding

**Answer:** The rule is commented out and you get css_unused_selector — No <li> exists in the component's own markup, so the compiler finds nothing to match. Write ul :global(li) to reach the injected ones.

- Not "The li elements from the HTML string get the padding": The compiler can't see elements inside an {@html} string, so they never get the scoping class and li.svelte-xyz doesn't match them.
- Not "Every li on the page gets the padding": That's what a nested <style> tag does. A top-level <style> block is always scoped.

## The class costs specificity

Adding `.svelte-lv9s7p` to a selector adds 0-1-0 to its specificity. The docs call this out: a component's `p` will "take precedence over a `p` selector defined in a global stylesheet, even if the global stylesheet is loaded later."[^scoped] I mounted the card, then appended `p { color: blue; font-weight: 100 }` to `<head>` after Svelte's own style tag. The card's paragraph stayed purple and bold.

That's the behavior you want for element selectors. The surprise is utility classes. I added `class="muted"` to the same paragraph with a global `.muted { color: gray }`. It stayed purple: `p.svelte-lv9s7p` is 0-1-1 and `.muted` is 0-1-0, so the type selector in the component beat the class from outside. If your app has a global utility sheet, a component's element rules will override it on that component's elements. [Effective CSS part 2](/writing/effective-css-2-the-cascade-specificity-and-inheritance/) has the specificity math in full.

The compiler does keep the bump to one class per selector. `.card p` came out as `.card.svelte-lv9s7p p:where(.svelte-lv9s7p)`, because `:where()` adds nothing, so a longer selector isn't penalized for having more parts.[^scoped]

Keyframes are scoped by the same hash. `@keyframes pulse` in the card became `svelte-lv9s7p-pulse`, and `animation: pulse 1s` in the same file was rewritten to match. A component that references a keyframe name it doesn't define, like `animation: spin 1s` with `spin` living in a global file, keeps the name as written, so global keyframes still work.

## Getting out on purpose

The escape hatch is `:global(...)`, and the useful form keeps one foot inside the component.[^global] This is the fix for my card:

```svelte title="Card.svelte"
<style>
  .card :global(.fancy) {
    color: red;
  }
</style>
```

It compiles to `.card.svelte-lv9s7p .fancy`: the `.card` has to be this component's element, and anything under it matching `.fancy` is fair game, whichever file rendered it. In my lab, the same pattern (`.card :global(.child)`) underlined the child's paragraph. The docs' example comment says the selector applies to elements "in any component" inside the scoped one, and that's the cost. A grandchild three components down with a `fancy` class matches as well.

The bare form, `:global(.fancy)` with nothing scoped in front, is a global stylesheet rule that happens to live in a component file. I keep those for `body` and theme hooks. `:global(.dark) .a` compiled to `.dark .a.svelte-706wz9`, which is a tidy way to let a class on `<html>` switch a component's colors without the component knowing where the class lives.

Part 9 already covered the other two ways a parent styles a child: the `:global { }` block, which compiles to native CSS nesting under a scoped selector, and passing `--custom-properties` to a component, which adds a `<svelte-css-wrapper>` element to your DOM.[^part9] I'd reach for custom properties first when I own the child, because the child decides which properties it reads, and `:global` when it's a library component I can't change.

For keyframes, the prefix is `-global-`: `@keyframes -global-spin` compiled to `@keyframes spin`, usable from anywhere.[^global]

## The `<style>` that isn't scoped

A component can have one top-level `<style>`. You can also put a `<style>` inside an element or a logic block, and Svelte inserts it "as-is" with "no scoping or processing."[^nested] I put `div { outline: 3px solid red }` in a nested `<style>` inside an `{#if}`. Every `div` on the page got an outline, including a `<div>` I'd created outside the component. Unmounting the component removed the tag and the outlines.

Compare that with the scoped sheet. After I unmounted the card, its `<style id="svelte-lv9s7p">` was still in `<head>`. Scoped CSS is per component, not per instance, so it's added once and left alone. The nested tag lives and dies with the markup around it, which makes it a way to load CSS conditionally, and I'd use it for nothing else.

## Hashed by file name

The scoped-styles page says the class is "based on a hash of the component styles."[^scoped] It was, until Svelte 5.38.9, which changed the default to hash the file name instead.[^hash] I compiled the same component twice as `A.svelte`, once with `color: red` and once with `color: blue`: both got `svelte-y1a51h`. The same CSS as `B.svelte` got `svelte-e55z3k`.

The issue behind the change said content hashes "change frequently between deployments."[^issue] Now editing a color doesn't rename every class in that component; renaming the file does. A full Vite 8.3.5 build with vite-plugin-svelte 7.3.1 used the same file-name hash and wrote the CSS to its own `.css` asset instead of injecting it from JavaScript.

## React leaves this to you

React has no built-in scoping. The docs say React "does not prescribe how you add CSS files," and `className` is a string you build yourself.[^react] The closest equivalent most React apps use is CSS Modules, which Vite supports out of the box: `.fancy` in `child.module.css` became `._fancy_1jekl_1` in my build, and the import gave me that string as `styles.fancy`.[^vite]

That difference matters more than it looks, because a CSS Modules class is a value. A React parent can pass `className={styles.fancy}` to any child, and it works, since nothing has to prove at build time that an element will carry it. Svelte's scoping is a compile-time match inside one file, which is why it can delete my `.fancy` rule and warn me about it, and why it can't follow a class across a component boundary. I'll take that trade. The warning has caught more dead CSS for me than the boundary has cost me workarounds.

CSS itself has a native answer now. `@scope` reached Baseline in March 2026, according to web-features 3.44.0, and Svelte compiles it fine: `@scope (.card) { p { … } }` came out with the inner `p` scoped and the `.card` root left alone.[^scope] It doesn't replace Svelte's scoping; it doesn't know about component files, and the compiler's hash doesn't need it.

**Quiz:** Your global CSS has .text-muted { color: gray }. A component's <style> has p { color: black }. You render <p class='text-muted'> in that component. What color is it?

- Gray, because a class beats a type selector
- Black
- Whichever stylesheet loads last

**Answer:** Black — The scoping class turns p into p.svelte-xyz. Load order doesn't matter: higher specificity wins. Style the paragraph by class in the component, or drop the p rule.

- Not "Gray, because a class beats a type selector": It would, outside Svelte. Inside the component, p becomes p.svelte-xyz, which is 0-1-1 and beats .text-muted at 0-1-0.
- Not "Whichever stylesheet loads last": Load order only breaks ties between equal specificities. These two aren't equal.

## What I'd take from this

Everything above comes from one rule: the compiler adds a class to the elements it can see in this file, and nothing else. The rule is why styles stay put, why unused selectors disappear with a warning, and why a child component, an `{@html}` string or a node you appended by hand are all outside. Before you reach for `:global`, ask whether the element you're styling belongs to this component. If it doesn't, a custom property, or a class the child styles itself, usually beats reaching into it.

Read the [scoped styles](https://svelte.dev/docs/svelte/scoped-styles) and [global styles](https://svelte.dev/docs/svelte/global-styles) pages; together they take five minutes. Then treat `css_unused_selector` as a bug report, not noise.

Next: SvelteKit, starting with routes and layouts.

[^scoped]: Svelte docs, [Scoped styles](https://svelte.dev/docs/svelte/scoped-styles).

[^global]: Svelte docs, [Global styles](https://svelte.dev/docs/svelte/global-styles).

[^nested]: Svelte docs, [Nested `<style>` elements](https://svelte.dev/docs/svelte/nested-style-elements).

[^part9]: [Part 9, "Styles across the component boundary"](/writing/why-svelte-9-svelte-best-practices-from-the-docs/). See also Svelte docs, [Custom properties](https://svelte.dev/docs/svelte/custom-properties).

[^hash]: [Svelte changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md), 5.38.9: "generate CSS hash using the filename" ([#16740](https://github.com/sveltejs/svelte/pull/16740)). The default `cssHash` in 5.57.2 is `svelte-${hash(filename ?? css)}`, falling back to the CSS when there's no file name.

[^issue]: [sveltejs/svelte#16636](https://github.com/sveltejs/svelte/issues/16636), "Hash styles by filename rather than contents."

[^react]: React docs, [Common components: applying CSS styles](https://react.dev/reference/react-dom/components/common#applying-css-styles).

[^vite]: Vite docs, [CSS Modules](https://vite.dev/guide/features#css-modules).

[^scope]: MDN, [`@scope`](https://developer.mozilla.org/en-US/docs/Web/CSS/@scope). Baseline date from the [web-features](https://github.com/web-platform-dx/web-features) package, which marks `@scope` newly available on 2026-03-24.

- **Part 12 — SvelteKit fundamentals: routes and layouts**: How a folder becomes a URL, how layouts nest and load data, and why SvelteKit keeps your page mounted when only the slug changes
