Skip to main content

Part 3 / Classes / The class directive

Like any other attribute, you can specify classes with a JavaScript attribute, seen here:

App.svelte
<button
	class={current === 'foo' ? 'selected' : ''}
	on:click={() => current = 'foo'}
>foo</button>

This is such a common pattern in UI development that Svelte includes a special directive to simplify it:

App.svelte
<button
	class:selected={current === 'foo'}
	on:click={() => current = 'foo'}
>foo</button>

The selected class is added to the element whenever the value of the expression is truthy, and removed when it's falsy.

Next: Shorthand class directive

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script>
	let current = 'foo';
</script>
 
<button
	class={current === 'foo' ? 'selected' : ''}
	on:click={() => (current = 'foo')}>foo</button
>
 
<button
	class={current === 'bar' ? 'selected' : ''}
	on:click={() => (current = 'bar')}>bar</button
>
 
<button
	class={current === 'baz' ? 'selected' : ''}
	on:click={() => (current = 'baz')}>baz</button
>
 
<style>
	.selected {
		background-color: #ff3e00;
		color: white;
	}
</style>
 
initialising