What is Dynamic CSS Binding in Vue.js

In Vue.js, binding CSS dynamically involves applying classes or inline styles to elements based on component data. This can be achieved using directives such as v-bind:class or :class for class binding and v-bind:style or :style for inline style binding. Let's explore these techniques with detailed code examples:

Class Binding

You can bind CSS classes dynamically to elements using the v-bind:class directive or its shorthand:class. Classes are specified as object keys, and their values are boolean expressions that determine whether the class should be applied.

<template>
  <div :class="{ active: isActive, 'error-text': hasError }">Dynamic CSS Binding</div>
</template>

<script>
export default {
  data() {
    return {
      isActive: true,
      hasError: false
    };
  }
}
</script>

<style>
.active {
  color: green;
}

.error-text {
  color: red;
  font-weight: bold;
}
</style>

In this example, the active class will be applied if isActive is true, and the error-text class will be applied if hasError is true.

Inline Style Binding

Inline styles can also be bound dynamically using the v-bind:style directive or :style shorthand. Styles are specified as objects, where the keys represent CSS properties, and the values are expressions that evaluate to the desired property values.

<template>
  <div :style="{ color: textColor, fontSize: fontSize + 'px' }">Dynamic Style Binding</div>
</template>

<script>
export default {
  data() {
    return {
      textColor: 'blue',
      fontSize: 16
    };
  }
}
</script>

In this example, the text color will be blue, and the font size will be 16px.

Computed Properties for CSS Binding

You can use computed properties to dynamically calculate CSS classes or inline styles based on component data. This approach is useful for more complex logic or when you need to reuse the CSS binding logic in multiple places.

<template>
  <div :class="computedClasses" :style="computedStyles">Computed CSS Binding</div>
</template>

<script>
export default {
  data() {
    return {
      isActive: true,
      hasError: false,
      fontSize: 20
    };
  },
  computed: {
    computedClasses() {
      return {
        active: this.isActive,
        'error-text': this.hasError
      };
    },
    computedStyles() {
      return {
        fontSize: this.fontSize + 'px'
      };
    }
  }
}
</script>

<style>
.active {
  color: green;
}

.error-text {
  color: red;
  font-weight: bold;
}
</style>

In this example, computedClasses dynamically calculates the classes to be applied, and computedStyles calculates the inline styles based on component data.

By using these techniques, you can dynamically apply CSS classes and inline styles in your Vue.js components based on changing data or component state, making your UI more flexible and responsive.