How to Add CSS in Svelte: Syntax and Examples
<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.
<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>
Example
This example shows a Svelte component with scoped CSS that styles a button. The button changes color when hovered.
<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>
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.
<!-- 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>Quick Reference
| CSS in Svelte | Description |
|---|---|
| Add scoped CSS inside the component file. | |
| :global(selector) { ... } | Apply global CSS styles outside the component scope. |
| Scoped styles | Automatically apply only to the component's HTML. |
| Use |