Svelte 36 🧡 Style Directives — style:property={value}
In modern web development, styling elements based on dynamic data—such as user-selected theme colors, interactive slider values, or element coordinates—is common. While standard CSS is static, the style: directive provides a declarative, reactive interface to inline styles. Instead of manipulating complex string templates inside a style="..." attribute, you can bind specific CSS properties directly to Svelte state variables.
This chapter covers the power of the style: directive, the efficiency of property-specific bindings, and the shorthand notation that makes responsive and dynamic design cleaner than ever. We will explore how these directives integrate with Svelte’s reactivity system to update the DOM precisely when your data changes.
Key point: The style: directive allows you to set CSS properties reactively; Svelte manages the application and removal of these styles automatically, keeping your templates free of messy string concatenation and providing an optimized path for CSS updates.
Why style directives exist
The string concatenation nightmare.
Building a style string like style="color: {color}; width: {width}px;" is brittle and difficult to debug. Small syntax errors, such as missing semicolons or units, can break the entire block. style: directives treat each property as a discrete, type-safe entity.
Performance of discrete updates.
When you update a large style attribute string, the browser may trigger a full style recalculation. Updating a specific property via the style: directive allows Svelte to patch just that specific CSS property, reducing layout thrashing.
Readability and maintainability.
Grouping dynamic properties into distinct directives makes the template structure clearer. You can easily spot which variables control which visual aspects of the element without parsing long strings.
The CSS variable integration.
style: directives are perfect for updating CSS Custom Properties (CSS variables). This allows you to centralize your design tokens and update them from within the component logic without touching individual child elements.
Reactive synchronization.
Because style: directives are reactive, they integrate seamlessly with the rest of your component logic. When the bound variable changes, Svelte updates the DOM node’s inline style property in the next tick.
a. The style:property={value} syntax
The syntax for the style: directive is style:property={value}. The “property” corresponds to a valid CSS property (e.g., color, background, font-size), and the “value” is any reactive Svelte expression.
<script>
let themeColor = "blue";
</script>
<div style:color={themeColor}>
This text changes color when themeColor updates.
</div>
Unlike the standard style attribute, you do not need to provide the full CSS syntax (like color: blue;). You only provide the value. If the variable is null or undefined, the style property is removed from the element, reverting it to its default or CSS-inherited state.
b. The shorthand style:property syntax
Similar to class:, Svelte supports shorthand for style directives. If the name of the variable matches the name of the CSS property exactly, you can omit the value. This is highly useful when using variables that follow standard CSS naming conventions.
<script>
let color = "red";
let opacity = 0.5;
</script>
<!-- If variable names match properties, shorthand works -->
<div style:color style:opacity>
Shorthand syntax for cleaner templates.
</div>
This reduces the noise in your templates significantly. It reinforces a convention where your state variables are named clearly, mapping directly to the styles they manipulate, which is a great practice for complex interactive components.
c. Mixing static styles and units
You can mix standard static style attributes with dynamic style: directives on the same element. Svelte intelligently merges them. Furthermore, you can append units directly to your values within the expression, making it easy to convert raw numbers from state into valid CSS dimensions.
<script>
let size = 20;
</script>
<!-- Static style mixes with reactive style directive -->
<div style="font-weight: bold" style:font-size="{size}px">
Combining static and dynamic styles.
</div>
This approach allows you to keep base styling (like font-weight) static while delegating high-frequency updates (like font-size) to the style: directive, resulting in a cleaner and more performant component structure.
Complete Example Session
// ============================================
// PART 1: BASIC COLOR BINDING
// ============================================
<script>
let primary = "green";
</script>
<p style:color={primary}>Text</p>
// ============================================
// PART 2: DYNAMIC UNITS (PIXELS)
// ============================================
<script>
let width = 100;
</script>
<div style:width="{width}px" style:background="blue"></div>
// ============================================
// PART 3: SHORTHAND PROPERTIES
// ============================================
<script>
let border = "1px solid black";
</script>
<div style:border></div>
// ============================================
// PART 4: MIXING STATIC AND DYNAMIC
// ============================================
<script>
let padding = 10;
</script>
<div style="margin: 5px" style:padding="{padding}rem"></div>
These parts show how to handle simple property binding, unit concatenation, shorthand usage, and combining static/dynamic styles.
Quick Reference
Directive Forms
| Syntax | Description |
|---|---|
style:prop={val} | Sets property to value |
style:prop | Shorthand if var matches name |
style="..." | Static inline styles |
style:prop={null} | Removes the style property |
Common Properties
| Property | Example Value |
|---|---|
color | 'red' |
width | '100px' |
background | '#fff' |
opacity | 0.5 |
display | 'flex' |
Best Practices
✅ Do This:
// Use directives for dynamic values
<div style:color={myColor} /> // ✅
// Add units during binding
<div style:width="{myWidth}px" /> // ✅
// Use shorthand when possible
<div style:opacity /> // ✅
// Keep complex math in reactive statements
$: size = base * multiplier; // ✅
❌ Don’t Do This:
// Avoid manual string interpolation
<div style="color: {color}; width: {width}px;" /> // ❌
// Don't use directives for static properties
<div style:color="red" /> // Use standard style attribute // ❌
// Don't forget to handle null/undefined
<div style:color={userColor || 'black'} /> // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Style not applying | Missing unit | Add "px", "rem", etc |
| Syntax error | Including colon in prop | Use style:color, not style:color: |
| Property removal | Passing empty string | Use null or undefined |
| Performance | Style updates in onMount | Use reactivity |
Real-World Examples
1. Dynamic Theme
<div style:color={theme.text} style:background={theme.bg} />
2. Progress Bar
<div style:width="{progress}%" />
3. Image Zoom
<img style:transform="scale({scale})" />
4. Interactive Palette
<button style:background={color} />
5. Layout Spacing
<div style:margin-left="{gap}px" />
6. Dynamic Opacity
<div style:opacity={isVisible ? 1 : 0} />
7. CSS Variable Update
<div style:--main-color={val} />
8. Element Visibility
<div style:display={show ? 'block' : 'none'} />
9. Font Control
<p style:font-size="{fontSize}pt" />
10. Floating Label
<label style:top="{y}px" />
Visual
Directive Binding Flow
┌──────────────────────────────────────────────┐
│ Variable Directive CSS Property │
│ color = "red" ──► style:color ──► color: red│
│ │
│ Update reactive state, Svelte patches DOM │
└──────────────────────────────────────────────┘
Mixing Static and Dynamic
┌──────────────────────────────────────────────┐
│ Static: style="font-size: 16px" │
│ Dynamic: style:color={userColor} │
│ │
│ Merged Result: style="font-size: 16px; color: red"│
└──────────────────────────────────────────────┘
CSS Variable Integration
┌──────────────────────────────────────────────┐
│ CSS: .box { background: var(--bg) } │
│ Svelte: <div style:--bg={color} /> │
│ │
│ Result: Reactive theme injection │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Directive Syntax | style:property={value} |
| Shorthand | style:property |
| Performance | High (Property-specific) |
| Readability | Excellent |
| Units | Manual (+ 'px') |
Key takeaways:
- Directives are clean and reactive. They allow you to bind specific CSS properties to Svelte state, bypassing the need for error-prone string manipulation.
- Use shorthand for consistency. When your variables match the CSS property names, use the shorthand
style:propertyto reduce template clutter. - Merge wisely. Combine static
style="..."for global, unchanging properties andstyle:directives for state-driven updates. - Remember units. Unlike numbers, CSS measurements require units (like
px,rem,%); remember to concatenate them in your expression. - Use for CSS variables. The
style:directive is the ideal way to update CSS Custom Properties reactively across your app.
Remember: The style: directive is the standard for dynamic UI styling in Svelte. It improves performance by avoiding complete attribute overwrites, enhances readability by isolating dynamic properties, and keeps your component logic clean and declarative.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!