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 -->
<script>
    import Button from 'Button.svelte';
</script>

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

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 -->

<button>
    Click me!
</button>

<style>
    background-color: var(--backdrop);
    color: var(--text);
</style>

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 -->
<script>
    import Button from 'Button.svelte';
</script>

<Button
    --backdrop="white"
    --text="blue"
/>

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.