Conditional Classes in Svelte
Glissez pour afficher le 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.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion