The class directive
Like any other attribute, you can specify classes with a JavaScript attribute.
<button
class="card"
class:flipped={flipped}
on:click={() => flipped = !flipped}
>
Shorthand class directive
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
Box.svelte
<div class="box" />
<style>
.box {
width: 5em;
height: 5em;
border-radius: 0.5em;
margin: 0 0 1em 0;
background-color: var(--color, #ddd);
}
</style>
App.svelte
<script>
import Box from './Box.svelte';
</script>
<div class="boxes">
<Box --color="red" />
<Box --color="green" />
<Box --color="blue" />
</div>