← Back to all tutorials

Dynamic CSS Classes

Dynamically add and remove CSS classes using v-bind:class — toggle styles based on data with object and array syntax.

Dynamic CSS Classes

Vue makes it easy to dynamically toggle CSS classes based on your data. Using v-bind:class (or :class), you can conditionally apply classes without any JavaScript DOM manipulation.

Object Syntax

<div :class="{ active: isActive, 'text-danger': hasError }">
    Dynamic classes
</div>

data: {
    isActive: true,
    hasError: false
}

<!-- Renders as: <div class="active"> -->

The object syntax passes an object where keys are class names and values are booleans. If the value is truthy, the class is applied. If falsy, it is removed.

Array Syntax

<div :class="[activeClass, errorClass]"></div>

data: {
    activeClass: 'active',
    errorClass: 'text-danger'
}

<!-- Renders as: <div class="active text-danger"> -->

Combining Static and Dynamic Classes

<div class="card" :class="{ featured: isFeatured }"></div>
<!-- Renders as: <div class="card featured"> when isFeatured is true -->

Computed Classes

computed: {
    cardClasses() {
        return {
            active: this.isActive,
            featured: this.isFeatured,
            'bg-success': this.rank > 5,
            'bg-warning': this.rank <= 5
        };
    }
}

<div :class="cardClasses"></div>

Dynamic Inline Styles

<div :style="{ color: textColor, fontSize: fontSize + 'px' }">
    Styled text
</div>

data: {
    textColor: 'red',
    fontSize: 24
}

Note: CSS property names use camelCase (fontSize) instead of kebab-case (font-size) when used as JavaScript object keys.

Key Takeaways

  • :class="{ className: condition }" toggles classes based on boolean conditions
  • Object syntax is best for toggling; array syntax for listing multiple classes
  • Static class and dynamic :class can coexist on the same element
  • :style binds inline styles using camelCase property names