In this note we will deal with CSS classes and styling.
Like any other attribute, you can specify classes with a JavaScript attribute. A simple conditional class attribute can be written as:
<button
class="card {flipped ? 'flipped' : ''}"
onclick={() => flipped = !flipped}
>This works as expected. This means that when the flipped state has a truthy value, we add the class 'flipped' to the class attribute. But we can make it nicer. Classes in Svelte can be an object or an array, that is converted to a string using clsx.
ex.
<button
class={["card", { flipped }]}
onclick={() => flipped = !flipped}
>This means ‘always add the card class, and add the flipped class whenever flipped is truthy’.
Consult https://svelte.dev/docs/svelte/class for the documentation.
The style directive
We can use the style: directive in Svelte to write our styles cleanly.
ex.
instead of this, which looks a bit wacky..
<button
class="card"
style="transform: {flipped ? 'rotateY(0)' : ''}; --bg-1:palegoldenrod; --bg-2: black; --bg-3: goldenrod;"
onclick={() => flipped = !flipped}
>..we could do something like this, which is tidier.
<button
class="card"
style:transform={flipped ? 'rotateY(0)' : ''}
style:--bg-1="palegoldenrod"
style:--bg-2="black"
style:--bg-3="goldenrod"
onclick={() => flipped = !flipped}
>Component styles
Often, you need to influence the styles inside a child component. We can always use the :global CSS modifier, which allows us to indiscriminately target elements inside other components. But, the docs recommend NOT to use it, as it can be considered as an escape hatch; and we can have a nicer method to declare component styles using a CSS custom property.
ex. inside Box.svelte
<div class="box"></div>
<style>
.box {
width: 5em;
height: 5em;
border-radius: 0.5em;
margin: 0 0 1em 0;
background-color: var(--color);
}
</style>and inside App.svelte
<script>
import Box from './Box.svelte';
</script>
<div class="boxes">
<Box --color="red"/>
<Box --color="green"/>
<Box --color="blue"/>
</div>This allows us to declaratively assign values of any CSS variable. The values can also be dynamic, like any other attribute.