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

Conditional Classes in Svelte

Svep för att visa menyn

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 7

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 7
some-alt