0
0
Svelteframework~5 mins

Global vs scoped style strategies in Svelte

Choose your learning style9 modes available
Introduction

Styles control how your app looks. Global styles affect everything, while scoped styles only change specific parts. This helps keep your design neat and avoids surprises.

When you want a consistent look across the whole app, like fonts or colors.
When styling a single component without affecting others.
When you want to avoid style conflicts between components.
When you need quick fixes that apply everywhere.
When building reusable components that should keep their own style.
Syntax
Svelte
<style global>
  /* Global styles */
  h1 {
    color: blue;
  }
</style>

<style>
  /* Scoped styles */
  p {
    color: red;
  }
</style>

In Svelte, styles inside a component are scoped by default, meaning they only apply to that component.

To make styles global, use the :global() selector or place styles in a global CSS file.

Examples
This style is scoped by default and only affects <h1> inside this component.
Svelte
<style>
  h1 {
    color: green;
  }
</style>
This style applies globally to the whole page's body, not just this component.
Svelte
<style>
  :global(body) {
    margin: 0;
    font-family: sans-serif;
  }
</style>
Using global attribute on <style> makes all styles inside global.
Svelte
<style global>
  a {
    text-decoration: none;
  }
</style>
Sample Program

This Svelte component shows a button with scoped styles that only affect it. The paragraph below uses a global style, so all paragraphs on the page get the green bold text.

Svelte
<script>
  let count = 0;
</script>

<style>
  button {
    background-color: lightblue;
    border: none;
    padding: 0.5rem 1rem;
    cursor: pointer;
  }

  /* Scoped style: only this button */
  button:hover {
    background-color: deepskyblue;
  }

  /* Global style: applies to all paragraphs */
  :global(p) {
    color: darkgreen;
    font-weight: bold;
  }
</style>

<button on:click={() => count++} aria-label="Increment count">
  Clicked {count} times
</button>

<p>This paragraph is styled globally.</p>
OutputSuccess
Important Notes

Scoped styles prevent your component styles from leaking out and affecting other parts of your app.

Use global styles carefully to avoid unexpected changes across your app.

Use :global() inside scoped styles to target global elements without losing scoping benefits.

Summary

Scoped styles apply only inside the component, keeping styles isolated.

Global styles affect the whole app or page, useful for common design rules.

Svelte makes styles scoped by default, but you can use :global() or global attribute for global styles.