How to Use Scoped Styles in Svelte: Syntax and Examples
<style> tag within your component file. These styles automatically apply only to that component, preventing them from affecting other parts of your app.Syntax
To create scoped styles in Svelte, write CSS inside a <style> tag in your component file. Svelte automatically scopes these styles to the component by adding unique attributes behind the scenes.
This means you do not need special syntax or keywords; just write normal CSS inside the <style> tag.
<script> let color = 'blue'; </script> <style> p { color: var(--text-color, black); font-weight: bold; } </style> <p style="--text-color: {color}">This text is styled and scoped.</p>
Example
This example shows a Svelte component with scoped styles. The paragraph text is blue and bold. The styles only apply inside this component and won't affect other components.
<script> let color = 'blue'; </script> <style> p { color: blue; font-weight: bold; } </style> <p>This text is blue and bold because of scoped styles.</p>
Common Pitfalls
1. Forgetting that styles are scoped: Styles inside <style> only affect the current component, so global styles need a different approach.
2. Trying to style child components: Scoped styles do not cross component boundaries. To style children, use global styles or pass props.
3. Using global incorrectly: To write global CSS inside a component, wrap styles with :global(). Without it, styles remain scoped.
/* Wrong: This won't style elements outside this component */ p { color: red; } /* Right: Use :global() to apply global styles */ :global(body) { margin: 0; font-family: sans-serif; }
Quick Reference
- Write CSS inside
<style>tags in your Svelte component for scoped styles. - Use
:global()to apply styles globally from inside a component. - Scoped styles prevent CSS conflicts by applying only to the component.
- Use CSS variables or props to customize styles dynamically.