0
0
SvelteHow-ToBeginner · 4 min read

How to Use Class Directive in Svelte: Simple Guide

In Svelte, use the class:classname={condition} directive to add a CSS class only when the condition is true. This lets you toggle classes dynamically in your HTML elements without manual string manipulation.
📐

Syntax

The class directive in Svelte uses the pattern class:classname={condition}. Here, classname is the CSS class you want to toggle, and condition is a JavaScript expression that evaluates to true or false. When the condition is true, the class is added; when false, it is removed.

svelte
<div class:active={isActive}>Toggle my class</div>
Output
<div>Toggle my class</div> (with class 'active' added if isActive is true)
💻

Example

This example shows a button that toggles a CSS class highlight on a text paragraph when clicked. The class changes the text color to red.

svelte
<script>
  let isHighlighted = false;
  function toggleHighlight() {
    isHighlighted = !isHighlighted;
  }
</script>

<style>
  .highlight {
    color: red;
    font-weight: bold;
  }
</style>

<button on:click={toggleHighlight} aria-pressed={isHighlighted}>
  Toggle Highlight
</button>
<p class:highlight={isHighlighted}>
  This text will be highlighted when the button is clicked.
</p>
Output
A button labeled 'Toggle Highlight' and a paragraph. Clicking the button toggles the paragraph's text color to red and bold.
⚠️

Common Pitfalls

One common mistake is trying to use the class directive with dynamic class names directly, like class:{dynamicClass}={true}, which is not supported. The class name must be a fixed identifier.

Also, avoid manually concatenating class strings when the class directive can handle conditional classes more cleanly.

svelte
<!-- Wrong way: dynamic class name -->
<script>
  let dynamicClass = 'active';
</script>
<div class:{dynamicClass}={true}>This will cause an error</div>

<!-- Right way: fixed class name -->
<div class:active={true}>This works fine</div>
Output
The first div causes a compile error; the second div renders with class 'active'.
📊

Quick Reference

  • class:classname={condition} adds classname if condition is true.
  • Use multiple class: directives on one element to toggle several classes.
  • Class names must be fixed identifiers, not variables.
  • Works well with boolean variables or expressions.

Key Takeaways

Use class:classname={condition} to toggle CSS classes based on state.
Class names in the directive must be fixed, not dynamic variables.
Multiple class directives can be combined on one element for complex styling.
Avoid manual string concatenation for classes when the directive handles it cleanly.
The directive updates classes reactively as conditions change.