0
0
SvelteHow-ToBeginner · 3 min read

How to Add CSS in Svelte: Syntax and Examples

In Svelte, you add CSS by placing styles inside a <style> tag within your component file. These styles are scoped to the component by default, meaning they only apply to that component's HTML.
📐

Syntax

To add CSS in Svelte, use the <style> tag inside your .svelte file. Styles inside this tag are scoped to the component automatically. You can also add global styles using the :global() selector.

svelte
<script>
  // Your component logic here
</script>

<style>
  /* Scoped styles apply only to this component */
  h1 {
    color: blue;
  }

  /* Global styles affect the whole app */
  :global(body) {
    margin: 0;
    font-family: sans-serif;
  }
</style>

<h1>Hello Svelte</h1>
Output
A blue colored heading 'Hello Svelte' appears on the page with the body having no margin and a sans-serif font.
💻

Example

This example shows a Svelte component with scoped CSS that styles a button. The button changes color when hovered.

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

<style>
  button {
    background-color: #6200ee;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 0.25rem;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  button:hover {
    background-color: #3700b3;
  }
</style>

<button on:click={() => count++} aria-label="Increment count">
  Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Output
A purple button labeled 'Clicked 0 times' that increments the count and changes color to a darker purple when hovered.
⚠️

Common Pitfalls

1. Forgetting that styles are scoped: Styles inside <style> only affect the component unless you use :global(). Trying to style child components directly won't work.

2. Using global styles without :global(): To style elements outside the component, wrap selectors in :global(). Otherwise, styles won't apply.

3. Overriding styles from external CSS: Scoped styles have higher specificity, so external CSS might not override them unless marked !important or using global styles.

svelte
<!-- Wrong: This won't style body globally -->
<style>
  body {
    background-color: lightgray;
  }
</style>

<!-- Right: Use :global() to style body -->
<style>
  :global(body) {
    background-color: lightgray;
  }
</style>
Output
The first style does not change the body's background color; the second style changes the body's background color to light gray globally.
📊

Quick Reference

CSS in SvelteDescription
Add scoped CSS inside the component file.
:global(selector) { ... }Apply global CSS styles outside the component scope.
Scoped stylesAutomatically apply only to the component's HTML.
Use