Custom Style Properties in Svelte

- 2 minutes read

Consider the following Panel.svelte Svelte component, which renders a child component called Button.svelte:

<!-- Panel.svelte -->
    import Button from 'Button.svelte';

<div style="--backdrop: white; --text: blue">
    <Button />

The above component passes some custom CSS variables to Button.svelte via a parent div’s style property.

This is because style properties cannot be directly attached to custom components in Svelte.

The Button.svelte component could look something like this:

<!-- Button.svelte -->

    Click me!

    background-color: var(--backdrop);
    color: var(--text);

However, instead of passing these CSS variables from the parent component to Button.svelte using a parent element’s style property, you could instead use Svelte’s custom style prop feature:

<!-- Panel.svelte -->
    import Button from 'Button.svelte';


Notice how the name of each CSS variable becomes a key and how each corresponding CSS value becomes the associated value.

Furthermore, notice how we no longer need a parent element, such as a styled div, to wrap around the Button element and apply styles to it.

The above Panel.svelte implementation will have exhibit the same functionality as this article’s initial Panel.svelte component. Nothing needs to change within Button.svelte. Neat, right?

Link to this section Conclusion

Anyway, hopefully using these custom style properties help make your Svelte code look a bit more clean and organized!

Thanks for reading.