0
0
Svelteframework~5 mins

Dynamic inline styles in Svelte

Choose your learning style9 modes available
Introduction

Dynamic inline styles let you change how elements look right inside your code. You can make styles update automatically when things change.

You want to change colors or sizes based on user actions.
You need to update styles depending on data or variables.
You want quick style changes without writing separate CSS classes.
You want to animate or highlight elements dynamically.
You want to keep style logic close to your component code.
Syntax
Svelte
<element style="property: {variable};">Content</element>
Use curly braces {} inside the style attribute to insert JavaScript variables or expressions.
You can add multiple styles by separating them with semicolons inside the style string.
Examples
This sets the text color dynamically using the textColor variable.
Svelte
<div style="color: {textColor};">Hello</div>
Multiple styles change based on bgColor and padding variables.
Svelte
<button style="background-color: {bgColor}; padding: {padding}px;">Click me</button>
Uses a condition to set font weight dynamically.
Svelte
<p style="font-size: {fontSize}px; font-weight: {isBold ? 'bold' : 'normal'};">Text</p>
Sample Program

This Svelte component shows a button that changes its background color when clicked. The color switches between blue and green. The button text also updates to show if it is active or inactive.

Svelte
<script>
  let isActive = false;
  let color = 'blue';
  function toggle() {
    isActive = !isActive;
    color = isActive ? 'green' : 'blue';
  }
</script>

<button on:click={toggle} style="background-color: {color}; color: white; padding: 1rem; border: none; border-radius: 0.5rem;">
  {isActive ? 'Active' : 'Inactive'}
</button>
OutputSuccess
Important Notes

Remember to keep style values as strings or expressions that produce strings.

Dynamic inline styles are great for quick changes but for many styles, consider CSS classes for better organization.

Summary

Dynamic inline styles let you update element styles using variables inside your Svelte components.

Use curly braces inside the style attribute to insert dynamic values.

This helps create interactive and responsive UI elements easily.