Ever changed the colour of p for one card, and every paragraph in the app changed with it? In Svelte that rarely happens. A component's CSS goes in the <style> tag of the component's own file. These styles are automatically scoped: they only reach the elements that component owns. You saw a glimpse of this in the Your First Svelte Component lesson. Here we look at it up close. We also look at three more tools: class: (puts a class on when a condition is true), style: (fills one CSS property from data) and :global() (a rule that applies outside the component).
Picture the chalk menu board at Mrs. Sri's stall. Mrs. Sri decorates her own board, and her chalk never reaches the board of the stall next door. To mark the dish a customer picked, she sticks one "Chosen" sticker on it and moves it from dish to dish. For an announcement to the whole street, she hangs a banner everyone can see. In code, the board is the scoped <style>, the movable sticker is class:, and the banner is :global().
Scoped styles, up close
This is the App.svelte of Mrs. Sri's stall. App mounts the Greeting component from the Svelte Props lesson, then three menu cards you can pick:
<script>
import Greeting from "./Greeting.svelte"
let menu = ["Fried Rice", "Chicken Noodles", "Iced Tea"]
let selected = $state("Fried Rice")
</script>
<h1>Mrs. Sri's Stall</h1>
<Greeting name="Sinta" />
{#each menu as name (name)}
<button class="card" class:active={selected === name} onclick={() => (selected = name)}>{name}</button>
{/each}
<p>Your pick: {selected}</p>
<style>
p { color: gray; }
.card { margin-right: 6px; padding: 6px 12px; border: 2px solid #d1d5db; border-radius: 8px; background: white; }
.active { border-color: #c2410c; background: #fff7ed; }
</style>
selected changes every time a card is clicked, so it's made with $state. menu never changes, so a plain let is enough. The class:active attribute on the button is covered in the next section.
The compiler turns the style into CSS roughly like this (cut short here):
p.svelte-zvbkrd{color:gray}.card.svelte-zvbkrd{margin-right:6px;...}.active.svelte-zvbkrd{border-color:#c2410c;background:#fff7ed}
And the DOM becomes:
<h1>Mrs. Sri's Stall</h1>
<p>Welcome, Sinta!</p>
<button class="card svelte-zvbkrd active">Fried Rice</button>
<button class="card svelte-zvbkrd">Chicken Noodles</button>
<button class="card svelte-zvbkrd">Iced Tea</button>
<p class="svelte-zvbkrd">Your pick: Fried Rice</p>
svelte-zvbkrdis the scope class: a class name the compiler makes by itself for this component. The compiler computes it from the component's file name. When the compiler isn't given a file name, as in the exercise editor, it computes the class from the text of<style>, so the class changes when the CSS changes.- Every selector gets that class once, for example
pbecomesp.svelte-zvbkrd. Every App element that can match one of the selectors gets the class too. - Greeting's paragraph doesn't have that class, so it stays black even though App has a
prule.<h1>doesn't get it either, since there is no rule forh1.
class:active: a class that switches on and off
class:active={condition} is the class: directive. This directive adds the active class while the condition is true and removes it while it is false. Other classes on the element are left alone. In the code above, the condition is selected === name, so only the card whose name equals selected gets active:
| Event | selected |
Fried Rice card | Chicken Noodles card |
|---|---|---|---|
| Start | "Fried Rice" |
card svelte-zvbkrd active |
card svelte-zvbkrd |
| Click Chicken Noodles | "Chicken Noodles" |
card svelte-zvbkrd |
card svelte-zvbkrd active |
class="card"stays on.class:activeonly adds or removesactive.- Shorthand: when the variable has the same name as the class,
class:active={active}can be writtenclass:active. In the exercise, you use that form:let active = true, then<p class:active>.activenever changes, so a plainletis enough. - One element can have several
class:directives, for exampleclass:active={selected === name} class:soldout={stock === 0}. - Writing a string,
class="card {selected === name ? 'active' : ''}", works too. Butclass:is shorter and says what it means more clearly.
Other options: since Svelte 5.16 (the exercise editor's version), the class attribute can hold an object or an array. The Svelte docs now suggest this form for new code, because it is more flexible than class:. All three ways in this table give the same classes, card active, on the selected card:
| Way | Example | When to pick it |
|---|---|---|
class: |
class="card" class:active={selected === name} |
One or two classes that switch on and off. It also works in Svelte 4, and this lesson's exercise checks for this form. |
| object | class={{ card: true, active: selected === name }} |
Several classes, each with its own condition. |
| array | class={["card", { active: selected === name }]} |
Classes that are always on plus conditional ones, or joining your classes with a class the parent passes in through props. |
Unused selectors are dropped
The compiler only reads that component's markup. A selector that can't match any element in that markup is dropped from the CSS, and the compiler warns:
Unused CSS selector ".active"
- If you remove
class:activefrom the cards, no element in the markup can carry theactiveclass. So the.activerule no longer applies in the compiled CSS. - Then if the
activeclass is added from JavaScript, for example withcard.classList.add("active")(cardhere is a variable that holds the button element), there is no rule left to use. The card's border stays grey. Put the class in the markup, throughclass:active. - The same warning catches typos:
.actvein the style while the markup saysactive.
:global(): leaving the scope on purpose
Sometimes a rule really must apply outside the component. For example a rule for body, or for what {@html} inserts, which gets no scope class. Wrap the selector in :global(...):
<style>
:global(body) { margin: 0; }
:global(p) { color: gray; }
.description :global(strong) { color: #c2410c; }
</style>
:global(body)is printed asbody{margin:0}with no scope class, so it applies to the whole page.:global(p)in App is printed asp{color:gray}. Greeting's paragraph turns grey too, and so does every other<p>in the app..description :global(strong): the.descriptionpart stays scoped, and only thestronginside it gets no scope class. It's the safest way to style what{@html}inserts.
style: for one property
style:property={value} fills one inline CSS property (written in the element's style attribute) from JavaScript:
<script>
let size = $state(24)
let closed = $state(false)
</script>
<h1 style:font-size="{size}px" style:color={closed ? "gray" : null}>Mrs. Sri's Stall</h1>
- The result is
<h1 style="font-size: 24px;">.sizeis made with$state, so as soon as it changes to 28, the heading grows with it. - A
nullorundefinedvalue removes the property. Socoloronly appears whileclosedistrue. - Use
style:for values that change with data. A look that never changes belongs in<style>.
Exercise: a blue paragraph
In the exercise, the starter is <p>Blue text</p>. The answer:
<script>
let active = true
</script>
<p class:active>Blue text</p>
<style>
p { color: gray; }
.active { color: blue; }
</style>
The compiler prints roughly p.svelte-150wy2m{color:gray}.active.svelte-150wy2m{color:blue}, and the paragraph becomes <p class="svelte-150wy2m active">.
- Both rules match that paragraph, and the more specific one wins. In CSS, a class is stronger than an element name.
.active.svelte-150wy2mhas two classes, whilep.svelte-150wy2mhas only one class and one element name. So the colour is blue,rgb(0, 0, 255), in whichever order the rules are written. - The checker looks for
class:and<style>in your code, then reads the paragraph's colour.
Older code: the styles are the same
Svelte 4 code still appears in tutorials and older repos. In that code, the scoped <style>, class:, style: and :global() are written exactly the same. Only the script and the events differ: let selected = "Fried Rice" with no $state, and on:click={...} where you write onclick={...}. One thing exists only in newer code: a class attribute written as an object, class={{ card: true, active: selected === name }}, which only exists since Svelte 5.16. So you won't find it in older code. It means the same as class="card" class:active={selected === name}.
⚠️ Styles that miss, or hit too much
- A class added with
classList.add("active")gets no scoped style when the markup has noclass:active. The compiler already dropped.activewith anUnused CSS selectorwarning. Useclass:activein the markup. :global(p)hits every paragraph in the app, other components' included. Limit it through a parent element:.description :global(p).- In the exercise, the order of the rules doesn't decide the colour.
.activestill beatspeven when written first, because it is more specific. - In the exercise, a paragraph turned blue only through a
style="color: blue"attribute doesn't pass. The checker looks forclass:and<style>in your code.
TL;DR: CSS in a component's <style> is scoped automatically: it only reaches the elements that component owns. To do this, the compiler adds a scope class like svelte-zvbkrd to every selector and to the elements that component owns, so styles don't leak into other components. The directive class:active={condition} adds the active class while the condition is true and removes it while it is false. When the variable has the same name as the class, class:active is enough. Selectors that match no element in the markup are dropped with an Unused CSS selector warning, so a class added from JavaScript gets no style. :global(selector) leaves the scope on purpose, for example :global(body), which applies to the whole page. style:font-size="{size}px" fills one CSS property from data, and a null value removes it. Svelte 4 code writes this styling part exactly the same. The exercise: let active = true, <p class:active>Blue text</p>, and a <style> holding p { color: gray; } then .active { color: blue; }, so the paragraph is blue.
⚡ Styles are scoped automatically
Guess first: App.svelte has the rule p { color: gray; }, and it mounts the Greeting component, which also holds a paragraph. Does Greeting's paragraph turn grey too?
No. The compiler turns the selector p into p.svelte-zvbkrd, and puts the class svelte-zvbkrd only on the elements App owns. Greeting's paragraph doesn't have that class, so it stays black.
Meaning: CSS in a component's <style> is scoped automatically: it only reaches the elements that component owns, and it doesn't leak into other components.
⚡ class: switches a class on and off
Write:
<button class="card" class:active={selected === name} onclick={() => (selected = name)}>{name}</button>
Meaning: This card button is written inside {#each menu as name}, so there is one card for each dish, and selected is a $state that holds the dish clicked last. The directive class:active={condition} adds the active class while the condition is true and removes it while it is false, so only the selected card gets active. class="card" stays on. When the variable has the same name as the class, class:active alone is enough.
⚡ Unused selectors are dropped
Guess first: <style> gives the active class an orange border. That class is added from JavaScript, card.classList.add("active") (the variable card holds the button element), with no class:active in the markup. Does the button's border turn orange?
No, it stays grey. No element in the markup can carry the active class, so the compiler already dropped the .active rule with an Unused CSS selector warning.
Meaning: The compiler only reads the component's markup, and it drops every selector that matches no element there. So put the class in the markup through class:. To leave the scope on purpose (so the rule also applies outside the component), wrap the selector in :global(...), such as :global(body).