By Kevin Åberg Kultalahti
2020-06-15

How to Use Variables in Style Tags in Svelte


This is a short article on how to solve a common issue that many newcomers face when they start using Svelte. By default you can’t use variables in the style tag, this shows you how to use an action to enable this functionality. Enjoy!

Let’s dive right in. Here’s the action:

export function styles(node, styles) {
	setCustomProperties(node, styles)
	
	return {
		update(styles) {
			setCustomProperties(node, styles)
		}
	};
}

function setCustomProperties(node, styles) {
	Object.entries(styles).forEach(([key, value]) => {
		node.style.setProperty(`--${key}`, value)
	})
}

Let’s try to understand what’s going on here. The styles are passed in as an object. Since this is just applying CSS custom properties it will actually behave as CSS - cascading down, etc.

To apply styles you pass in an object that contains your custom styles and it will create custom properties that are applied to the element in question. Here’s how you would apply it to an element:

<script>import { styles } from './styles.js'
	export let color = "pink";
</script>

<style>h1 {
		color: var(--color);
	}
</style>

<h1 use:styles={{ color: color }}>
	Child color is {color}
</h1>

Here’s a REPL that you can play around with. It shows you the cascading as well as how the variables are reactive.

Liking this content?
Sign up to the newsletter!

Inspired by kaisermann’s svelte-css-vars. If you don’t want to write your own actions, just use this, it’s a great little library!

Thanks for reading, I hope you learned something.

profile image

I'm Kevin. A (mostly) front-end web developer focusing only on Svelte. I write articles, create videos and make courses. I run the Svelte Radio podcast. Oh, and I like to build stuff; websites, packages, anything really. If you want to get in contact with me, hit me up on Twitter or send me an email.

Svelte School is a company that develops courses and trains developers on how to use the framework Svelte.