Passing CSS Custom Properties
You can pass both static and dynamic CSS custom properties to components:How It Works
The Svelte compiler transforms CSS custom properties into wrapper elements. The above code essentially desugars to:The
display: contents ensures the wrapper doesn’t affect layout. However, it will affect CSS selectors that use the > combinator to target an element directly inside the component’s container.SVG Elements
For SVG elements, Svelte uses a<g> element instead:
Using CSS Variables in Components
Inside the component, read these custom properties usingvar(...) with optional fallback values:
#aaa and blue) are used when the custom properties aren’t provided.
Inheriting from Parent Elements
You don’t have to specify values directly on the component. As long as custom properties are defined on a parent element, the component can use them:Global CSS Variables
It’s common to define custom properties on the:root element in a global stylesheet so they apply to your entire application:
Practical Examples
Themeable Card Component
Dark Mode Toggle
Dynamic Component Colors
CSS custom properties are a powerful way to create themeable, reusable components. They cascade through the component tree and can be overridden at any level.