0 day streak
javascript / intermediate
Snippet

Conditional Styling with Class Directives

The class:name={value} directive is a shorthand for toggling CSS classes based on a boolean expression. If the variable name matches the class name, you can use the even shorter class:active syntax.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
let isAdmin = true;
let isEnabled = false;
</script>
<div class:active={isEnabled} class:admin={isAdmin}>
User Profile
</div>
<style>
.active { color: green; }
.admin { font-weight: bold; }
</style>
svelte
Breakdown
1
class:active={isEnabled}
Applies the 'active' class only if isEnabled is truthy.
2
class:admin={isAdmin}
Applies the 'admin' class based on the isAdmin boolean.