Classes and styles

18/09/2024 by zavos.dev

Hello there, fellow Svelte enthusiasts!


In Svelte, you can dynamically apply classes and styles to elements using bindings and reactive statements, making it easy to create responsive and interactive designs.


The class directive

Like any other attribute, you can specify classes with a JavaScript attribute.

Flip the card

This directive means 'add the flipped class whenever flipped is truthy'.


    <button
	class="card"
	class:flipped={flipped}
	on:click={() => flipped = !flipped}>

Often, the name of the class will be the same as the name of the value it depends on.
In those cases we can use a shorthand form:


    <button
	class="card"
	class:flipped
	on:click={() => flipped = !flipped}>

The style directive

As with class, you can write your inline style attributes literally, because Svelte is really just HTML with fancy bits

When you have a lot of styles, it can start to look a bit wacky. We can tidy things up by using the style: directive


    <button
	class="card"
	style:transform={flipped ? 'rotateY(0)' : ''}
	style:--bg-1="palegoldenrod"
	style:--bg-2="black"
	style:--bg-3="goldenrod"
	on:click={() => flipped = !flipped}>

Component styles

Often, you need to influence the styles inside a child component. Perhaps we want to make these boxes red, purple and cyan.

Inside the child's component code we change background-color to var(--color, #ddd); so it can be determined by a Custom CSS property.


And now we can specify the desired color of our component inline using
--color="red"
	<Box --color="red">