Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Conditional Classes in Svelte | Section
Styling Svelte Applications with Tailwind CSS

Conditional Classes in Svelte

Swipe um das Menü anzuzeigen

Frontend applications often need to apply different styles depending on the current application state. Buttons may change color when active, validation messages may appear when errors exist, and themes may switch between light and dark modes.

Svelte makes dynamic styling simple by allowing classes to react to variables and conditions.

Applying Classes Dynamically

Open App.svelte and add the following code:

<script>
  let active = true;
</script>

<button
  class={active
    ? 'bg-purple-600 text-white'
    : 'bg-gray-300 text-black'}
>
  Status Button
</button>

The button styling changes depending on the value of active.

Updating Styles with User Interaction

Add a button click handler:

<script>
  let active = false;
</script>

<button
  on:click={() => active = !active}
  class={active
    ? 'bg-green-600 text-white'
    : 'bg-red-500 text-white'}
>
  Toggle Status
</button>

Each click updates the component state and changes the button styling automatically.

Combining Static and Dynamic Classes

Static utility classes can work together with dynamic classes.

<button
  class="
    px-4
    py-2
    rounded-lg
    {active
      ? 'bg-purple-600 text-white'
      : 'bg-gray-300 text-black'}
  "
>
  Dynamic Button
</button>

This approach keeps layouts and spacing consistent while still allowing state-based styling.

Real-World Examples

Conditional styling is commonly used for:

  • Active navigation links;
  • Validation states;
  • Theme toggles;
  • Selected filters;
  • Notifications;
  • Interactive dashboards.

Modern frontend applications rely heavily on dynamic visual feedback.

question mark

What will happen when the value of active changes in the following code?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 7

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 7
some-alt