Styling in Svelte (Scoped CSS, :global, and Class Directives)




Why Styling Matters 🎨

Code makes apps work, but styling makes them delightful.
Imagine a to-do app that functions perfectly — but everything is plain Times New Roman, unstyled checkboxes, and buttons straight out of 1995. It works… but no one wants to use it.

That’s where styling comes in. A clean, well-designed UI makes your app feel modern, usable, and trustworthy.

Svelte doesn’t just give you reactive components — it also gives you a built-in styling model. Unlike React (where you often reach for extras like CSS Modules or styled-components), Svelte treats styles as a first-class citizen, right inside your .svelte files.

👉 By the end of this guide, you’ll be able to:

  • Write scoped CSS that applies only to one component.
  • Escape the scope with :global when needed.
  • Use class directives for dynamic, reactive styling.
  • Supercharge your workflow with Tailwind CSS utilities.

Let’s begin with the foundation: scoped styles — Svelte’s secret to avoiding CSS spaghetti.




Step 1: Scoped CSS — The Svelte Way

Every Svelte component (.svelte file) can contain a block.
The key difference from plain HTML/CSS:

  • In regular HTML, a tag applies globally across the whole page.
  • In Svelte, a tag inside a component is scoped: it only affects the markup in that same file.

This is what makes component-based styling safe and predictable.




Example: A Styled Button

src/lib/Button.svelte