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

Conditional Classes in Svelte

Veeg om het menu te tonen

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?

Selecteer het correcte antwoord

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 7

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 1. Hoofdstuk 7
some-alt