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

Conditional Classes in Svelte

Deslize para mostrar o menu

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?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 7

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 1. Capítulo 7
some-alt