Svelte 35 🧡 Class Directives — class:name={condition} and Shorthand
Managing CSS classes based on component state is a routine task in web development. Traditionally, this involved complex string concatenation or helper libraries like clsx or classnames to keep strings clean. Svelte simplifies this entirely with the class: directive. This directive allows you to conditionally toggle classes on an element directly in the template, removing the need for manual string manipulation or ternary operators within the class attribute.
This chapter covers the standard class:name={condition} syntax, the power of the shorthand class:name syntax, and how to mix static and dynamic classes efficiently. We will also explore how to handle multiple conditional classes without cluttering your component’s HTML structure.
Key point: The class:name={condition} directive automatically adds the class name when the condition is truthy and removes it when falsy, providing a clean, declarative approach to reactive styling.
Why class directives exist
The concatenation mess.
Manually building class strings using class="btn " + (isActive ? "active" : "") is prone to errors, particularly with whitespace management. Directives handle this cleanly, ensuring no stray spaces or double-class definitions occur.
Reactive efficiency.
Svelte’s compiler tracks the condition inside the directive. When the state changes, Svelte updates the classList directly. This is more performant than re-rendering the entire class attribute string on every state change.
Readable templates.
By pulling conditional logic out of a long attribute string, templates remain readable. You can see at a glance exactly which conditions control which specific classes, improving maintainability.
The shorthand syntax.
When your variable name matches the CSS class name, Svelte allows you to omit the value entirely. This reduces verbosity, especially in components where state variables are named after the UI state they represent.
Seamless mixing.
You can mix standard static class="fixed-class" attributes with multiple class:dynamic directives on the same element. Svelte merges these correctly, providing a robust system for styling.
a. The standard class:name={condition} directive
The standard syntax takes the form class:class-name={condition}. The class name is the literal string that will be applied to the DOM, and the condition is any JavaScript expression that evaluates to a truthy or falsy value.
<script>
let isActive = false;
</script>
<div class:active={isActive}>
Content goes here
</div>
When isActive is true, the element renders as <div class="active">. When false, the class attribute is removed entirely. If the element already had other classes defined in a class="..." attribute, they are preserved, and the new class is added or removed dynamically.
b. The shorthand class:name syntax
If the variable name matches the desired class name, you can omit the value. This is a common pattern in Svelte components where state variables like selected or disabled map directly to CSS classes.
<script>
let selected = true;
let disabled = false;
</script>
<!-- If 'selected' is true, adds class="selected" -->
<button class:selected class:disabled>
Click Me
</button>
This shorthand significantly reduces noise in your templates. It enforces a convention where your component state names serve as your CSS class names, which can lead to a more consistent and predictable style architecture.
c. Combining static and dynamic classes
You can use a standard class attribute for classes that are always present, and multiple class: directives for state-dependent styling. Svelte handles the merging order, ensuring the static classes are always applied while the directives toggle their respective values.
<script>
let isError = true;
</script>
<div class="card" class:error={isError} class:highlight={!isError}>
This card has a static base class and two dynamic toggles.
</div>
This approach allows you to keep base styles (like layout or sizing) in the class attribute while moving state-based styles (like theme, status, or hover effects) into the class: directives, keeping your logic cleanly separated from your base styles.
Complete Example Session
// ============================================
// PART 1: BASIC CONDITIONAL CLASS
// ============================================
<script>
let isOpen = false;
</script>
<div class:open={isOpen}>Menu</div>
// ============================================
// PART 2: SHORTHAND SYNTAX
// ============================================
<script>
let active = true;
</script>
<li class:active>Option</li>
// ============================================
// PART 3: MIXING STATIC AND DYNAMIC
// ============================================
<script>
let loading = false;
</script>
<button class="btn" class:loading>Submit</button>
// ============================================
// PART 4: MULTIPLE CONDITIONS
// ============================================
<script>
let status = "success";
</script>
<div class:success={status === 'success'} class:fail={status === 'fail'}>
{status}
</div>
The examples cover basic toggling, shorthand notation for clean code, mixing classes for base-styles, and managing multiple states via logical expressions.
Quick Reference
Class Directives
| Syntax | Description |
|---|---|
class:name={cond} | Adds class if cond is true |
class:name | Shorthand if variable name is true |
class="..." | Static classes, always applied |
class:n1={c1} class:n2={c2} | Multiple toggles on one element |
Comparison
| Approach | Readability | Performance |
|---|---|---|
| String concatenation | Low | Low |
class: directive | High | High |
| Helper library | Moderate | Moderate |
Best Practices
✅ Do This:
// Use shorthand when variable names match
<div class:active={isActive} /> // Use <div class:active /> // ✅
// Mix static and dynamic classes
<button class="btn" class:primary={isPrimary} /> // ✅
// Use expressions for complex conditions
<div class:error={count > 10} /> // ✅
// Keep directives organized
<div class="box" class:hidden={isVoid} class:fade={isOut} /> // ✅
❌ Don’t Do This:
// Avoid manual string concatenation
<div class={'base ' + (isActive ? 'active' : '')} /> // ❌
// Don't mix different ways to manage classes
<div class:active={isActive} class="active" /> // ❌
// Avoid overly complex ternary in templates
<div class:x={a ? b ? c : d : e} /> // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Overlapping classes | Same class added twice | Use one directive |
| Confusing shorthand | Variable name doesn’t match | Use long form |
| Logic bloat | Complex ternary in directive | Use reactive variable |
| CSS conflicts | Order of CSS rules | Use specific selector |
Real-World Examples
1. Navigation Link
<a class:active={current === 'home'} />
2. Button Spinner
<button class:loading={isSubmitting} />
3. Error State
<input class:error={hasError} />
4. Selection Highlight
<li class:selected={id === targetId} />
5. Theme Toggle
<body class:dark={isDarkMode} />
6. Disabled State
<button class:disabled={!isValid} />
7. Success Banner
<div class="banner" class:success />
8. Interactive Tabs
<button class:tab-active={idx === current} />
9. Responsive Hidden
<div class:hidden={w < 600} />
10. Multi-Condition Alert
<div class:warn={val > 5} class:crit={val > 10} />
Visual
Directive Logic
┌──────────────────────────────────────────────┐
│ State Variable Directive DOM Class │
│ isActive = true ──► class:active ──► .active│
│ isActive = false ──► class:active ──► (none)│
└──────────────────────────────────────────────┘
The Merge Process
┌──────────────────────────────────────────────┐
│ Static: class="btn" │
│ Dynamic: class:loading={true} │
│ │
│ Merged Result: class="btn loading" │
└──────────────────────────────────────────────┘
Shorthand Mapping
┌──────────────────────────────────────────────┐
│ Variable Name: `selected` │
│ Directive: `class:selected` │
│ Logic: if selected == true │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Standard Syntax | class:name={cond} |
| Shorthand | class:name |
| Merging | Static + Dynamic |
| Performance | High (Compiled) |
| Readability | Excellent |
Key takeaways:
- Directives are reactive. Svelte automatically tracks the condition and updates the element’s class list whenever the state changes.
- Prefer shorthand. Use
class:namewhenever your state variable matches the CSS class name to minimize template noise. - Don’t mix strategies. Avoid combining manual string concatenation with
class:directives, as it creates unpredictable class lists. - Mix base styles and toggles. Use standard
class="..."for base styles andclass:directives for toggling state-based styles on the same element. - Use reactive variables for complexity. If your directive condition is a long ternary or logic chain, move it into a reactive
$:variable to simplify the template.
Remember: The class: directive is Svelte’s most efficient and idiomatic way to handle conditional styling. By moving from manual string concatenation to this declarative system, you make your code more readable, reduce performance overhead, and eliminate common bugs related to class string management.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!