Vue CSS Binding

🎨 Vue CSS Binding

In Vue.js, CSS binding lets you dynamically apply classes and styles to elements based on data, computed properties, or methods. This is done using v-bind (shorthand :).

 What is CSS Binding?

CSS binding means changing an element’s class or style reactively when Vue data changes—no manual DOM manipulation needed.

<p :class="activeClass">Hello Vue</p>

 Class Binding

1️⃣ Object Syntax (Most Common)

Apply classes conditionally with booleans.


active applied
error not applied


2️⃣ Array Syntax

Apply multiple classes dynamically.


3️⃣ Mixed Syntax (Array + Object)

<p :class="['card', { selected: isSelected }]">
Card Item
</p>

4️⃣ With Computed Properties (Best Practice)

<p :class="statusClass">User Status</p>
computed: {
statusClass() {
return {
online: this.isOnline,
offline: !this.isOnline
}
}
}

 Style Binding (Inline Styles)

1️⃣ Object Syntax


2️⃣ Object from Data

<p :style="styleObject">Hello Vue</p>
data() {
return {
styleObject: {
color: "green",
backgroundColor: "lightyellow"
}
}
}

3️⃣ Array Syntax (Multiple Style Objects)

<p :style="[baseStyle, overrideStyle]">Multi Style</p>

 CSS Binding with v-for

<li
v-for="item in items"
:key="item.id"
:class="{ active: item.active }"
>
{{ item.name }}
</li>

 Binding CSS for Common UI Cases

🔘 Disable Button Style

<button :class="{ disabled: isDisabled }" :disabled="isDisabled">
Submit
</button>

🔔 Error Highlight

<input :class="{ error: hasError }">

 Scoped CSS with Vue Components

<style scoped>
.active {
color: green;
}
.error {
color: red;
}
</style>

✔ Styles apply only to this component


class vs style Binding

Feature :class :style
Best for Reusable styles Dynamic inline values
Performance Better Slightly lower
Clean code ❌ (if overused)

✔ Prefer class binding
✔ Use style binding for dynamic values (px, %, colors)


 Common Mistakes ❌

❌ Using static class instead of binding
❌ Writing complex logic in template
❌ Overusing inline styles


 Best Practices ✅

✔ Use computed properties for class logic
✔ Keep CSS in .css / <style>
✔ Prefer class binding over style binding
✔ Use meaningful class names


 Summary Table

Task Syntax
Conditional class :class="{ active: isActive }"
Multiple classes :class="[a, b]"
Inline style :style="{ color: 'red' }"
Scoped CSS <style scoped>

 Conclusion

Vue CSS binding makes your UI dynamic, clean, and reactive.
Mastering :class and :style is essential for professional Vue UI development.

You may also like...