Chapter 7: Styling in Svelte

Svelte provides powerful and flexible styling capabilities. In this chapter, we'll explore component-scoped CSS, global styles, and dynamic styling techniques.

Component-Scoped Styles

One of Svelte's best features is that CSS in a component is automatically scoped to that component:

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

<div>
  <h1>Count: {count}</h1>
  <button on:click={() => count++}>Increment</button>
</div>

<style>
  div {
    background: #f0f0f0;
    padding: 1rem;
  }

  h1 {
    color: purple;
  }

  button {
    background: purple;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    cursor: pointer;
  }
</style>

The styles only apply to this component. Other components won't be affected!

Dynamic Styles

Use reactive variables in your styles:

<script>
  let isActive = false;
</script>

<div class:active={isActive}>
  Conditional class
</div>

<style>
  div {
    padding: 1rem;
  }

  .active {
    background: green;
    color: white;
  }
</style>

Inline Styles

Apply inline styles dynamically:

<script>
  let color = 'purple';
</script>

<div style="color: {color}; background: lightgray; padding: 1rem;">
  Dynamically styled text
</div>

Global Styles

Use :global() to apply global styles from a component:

<style>
  :global(body) {
    background: #f9f9f9;
  }

  :global(.utility-class) {
    margin: 1rem;
  }
</style>

Svelte's styling system is flexible and keeps your stylesheets organized!