In Svelte, there may be scenarios where you need to apply CSS properties to an element dynamically based on the value of a variable. While there are multiple ways to achieve this, I will demonstrate two commonly used methods.

Method 1: Adding an HTML Class

One straightforward solution is to add an HTML class to the element when the selected variable has a particular value. This can be achieved by writing CSS rules that target the element with the class.

<style>
 /* ...other CSS... */
 span.cell.selected {
   outline-color: lightblue;
   outline-style: dotted;
 }
</style>

<span class="cell {selected === true ? 'selected' : ''}">
 {value}
</span>

Method 2: Binding Class Name in Svelte

To simplify the process, Svelte introduced the ability to bind the class name directly to a variable value.

<span class="cell" class:selected="{selected}">
 {value}
</span>

This approach allows you to dynamically apply the selected class to the element when the selected variable is true.

An even more concise method is to use the shorthand notation.

<span class="cell" class:selected>
 {value}
</span>

Using class:selected as a shorthand notation achieves the same result as the previous method.

By leveraging these techniques, you can dynamically apply CSS styles to elements in your Svelte application. This comes in handy when you need to style elements based on changing conditions, providing a more interactive user experience.