Skip to content

Commit 343bef1

Browse files
committed
docs
1 parent 922c544 commit 343bef1

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

documentation/docs/03-template-syntax/16-class.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,64 @@
22
title: class:
33
---
44

5+
Svelte provides ergonomic helpers to conditionally set classes on elements.
6+
7+
## class
8+
9+
Since Svelte 5.15, you can pass an object or array to the `class` attribute to conditionally set classes on elements. The logic is as follows:
10+
11+
- Primitive: All truthy values are added, all falsy not
12+
- `Object`: All truthy keys are added to the element class
13+
- `Array`: Objects and primitives are handled according to the two previous descriptions, nested arrays are flattened
14+
15+
```svelte
16+
<!-- These are equivalent -->
17+
<div class={isCool ? 'cool' : ''}>...</div>
18+
<div class={{ cool: isCool }}>...</div>
19+
<div class={[ isCool && 'cool' ]}>...</div>
20+
```
21+
22+
You can use this to conditionally set many classes at once, including those that have special characters.
23+
24+
```svelte
25+
<!-- These are equivalent -->
26+
<div class={{ 'bg-blue-700 sm:w-1/2': useTailwind }}>...</div>
27+
<div class={[ useTailwind && 'bg-blue-700 sm:w-1/2' ]}>...</div>
28+
```
29+
30+
Since `class` itself takes these values, you can use the same syntax on component properties when forwarding those to the `class` attribute.
31+
32+
```svelte
33+
<!--- file: App.svelte --->
34+
<script>
35+
import Button from './Button.svelte';
36+
let useTailwind = $state(false);
37+
</script>
38+
39+
<Button
40+
onclick={() => useTailwind = true}
41+
class={{ 'bg-blue-700 sm:w-1/2': useTailwind }}
42+
>
43+
Give in
44+
</Button>
45+
```
46+
47+
```svelte
48+
<!--- file: Button.svelte --->
49+
<script>
50+
let { children, ...rest } = $props();
51+
</script>
52+
53+
<!-- rest contains class, and the value is appropriately stringified -->
54+
<button {...rest}>
55+
{@render children()}
56+
</button>
57+
```
58+
59+
Under the hood this is using [`clsx`](https://github.com/lukeed/clsx), so if you need more details on the syntax, you can visit its documentation.
60+
61+
## class:
62+
563
The `class:` directive is a convenient way to conditionally set classes on elements, as an alternative to using conditional expressions inside `class` attributes:
664

765
```svelte
@@ -21,3 +79,5 @@ Multiple `class:` directives can be added to a single element:
2179
```svelte
2280
<div class:cool class:lame={!cool} class:potato>...</div>
2381
```
82+
83+
> [!NOTE] Since Svelte 5.15, you have the same expressive power with extra features on the `class` attribute itself, so use that instead if possible

0 commit comments

Comments
 (0)