Class Directive
The class: directive toggles a CSS class from a value.
No string concatenation, no ternaries inside your class
attribute.
Basic Usage
Write class:name={value}. When the value is truthy the element gets
the class; when it is falsy the class is removed.
source
<script>
let active = false
</script>
<button class="toggle" onclick="active = !active">Toggle</button>
<p class="status" class:active={active}>
{active ? 'Active' : 'Inactive'}
</p>
<style>
.toggle {
border: 1px solid #a1a1aa;
border-radius: 6px;
padding: 0.35rem 0.9rem;
cursor: pointer;
}
.status {
display: inline-block;
margin-top: 0.75rem;
padding: 0.5rem 0.9rem;
border-radius: 6px;
background: #e4e4e7;
color: #3f3f46;
}
.status.active {
background: #16a34a;
color: #ffffff;
}
</style>
output
Inactive
Shorthand Syntax
When the class name matches the variable name, drop the value:
source
<script>
let active = true
</script>
<!-- Shorthand for class:active={active} -->
<div class:active>Highlighted while active is true</div>
Multiple Class Directives
Use as many as you need, alongside a plain class attribute.
Each one is independent.
source
<script>
let danger = false
let large = false
</script>
<button class="btn" class:btn-danger={danger} class:btn-large={large}>
Save changes
</button>
<div class="controls">
<button class="control" onclick="danger = !danger">Toggle danger</button>
<button class="control" onclick="large = !large">Toggle large</button>
</div>
<style>
.btn {
border: none;
border-radius: 6px;
padding: 0.4rem 0.9rem;
background: #2563eb;
color: #ffffff;
cursor: pointer;
}
.btn-danger {
background: #dc2626;
}
.btn-large {
font-size: 1.25rem;
padding: 0.7rem 1.4rem;
}
.controls {
display: flex;
gap: 0.5rem;
margin-top: 1rem;
}
.control {
border: 1px solid #a1a1aa;
border-radius: 6px;
padding: 0.3rem 0.7rem;
cursor: pointer;
}
</style>
output
The value can be any expression, not just a boolean
(
class:featured={score > 90}), and class names with hyphens
work as written (class:is-selected={selected}).
Why Not Ternary?
Compare these approaches:
source
<!-- Without class: directive -->
<div class="card {isActive ? 'active' : ''} {featured ? 'featured' : ''}">
<!-- With class: directive -->
<div class="card" class:active={isActive} class:featured>
The directive version is easier to read, and each class stays on its own line next to the condition that controls it.