Styling in Svelte: Scoped, Component, and Global Styles
Introduction to Styling in Svelte
Welcome to the first lesson of the Styling & Transitions in Svelte course! In this lesson, we’ll dive into the fundamentals of styling in Svelte, focusing on three key concepts: scoped styles, component styles, and global styles. Understanding these concepts is essential for creating clean, maintainable, and visually appealing user interfaces.
Svelte makes styling straightforward by allowing you to write CSS directly within your components. This approach ensures that styles are modular and scoped to the component by default, preventing unintended conflicts across your application. However, Svelte also provides flexibility for defining global styles when needed, ensuring you have the tools to handle any styling scenario.
By the end of this lesson, you’ll understand how to use scoped, component, and global styles effectively in Svelte. You’ll also see how these concepts work together in a practical example, preparing you for the practice exercises that follow.
Note: This lesson assumes you have a basic understanding of CSS. If you're new to CSS or need a refresher, we recommend taking one of our CSS Paths before proceeding. Additionally, we will specifically highlight what is unique to Svelte versus standard CSS.
Scoped Styles in Svelte
Scoped styles are the default way to style components in Svelte. When you write CSS inside a <style> block in a Svelte component, those styles are automatically scoped to that component. This means they won’t affect other components or elements outside of the current component.
Here’s an example of scoped styles in action:
In this example, the h1 element will be styled with a blue color, but only within this component. If you have another component with an h1 element, it won’t be affected by this style. This scoping mechanism helps avoid CSS conflicts and makes your styles more predictable.
Component Styles in Svelte
Component styles allow you to define styles that are specific to a component while also enabling customization through CSS variables. This is particularly useful when you want to create reusable components that can be styled dynamically.
Let’s look at an example using CSS variables:
In this example, the Box component uses a CSS variable (--color) to set its background color. Here’s how the Box.svelte component is defined:
The background-color property in the .box class uses the CSS var() function to apply the --color variable. If no value is provided for --color, it defaults to #ddd. This approach makes the Box component highly customizable and reusable.
