Vue.js Class and Style Binding

Vue.js makes it simple to bind dynamic CSS classes and inline styles to HTML elements. With the v-bind directive (or its shorthand :), you can apply styles or classes based on your application's reactive data. This feature helps keep your UI in sync with state changes while keeping your code clean and maintainable.



Binding HTML Classes

You can bind one or more classes to an element using v-bind:class or the shorthand :class. Vue supports binding classes in several formats: string, object, and array.

Binding a Class Using a String

Example:

<div id="app">
  <p :class="className">This is a paragraph.</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      className: 'highlight'
    }
  });
</script>

In this example, the paragraph will have the highlight class when className is set to 'highlight'.

Binding Classes Using an Object

Example:

<div id="app">
  <p :class="{ active: isActive, error: hasError }">Status Message</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      isActive: true,
      hasError: false
    }
  });
</script>

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

Binding Classes Using an Array

Example:

<div id="app">
  <p :class="[baseClass, isActive ? 'active' : '']">User Status</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      baseClass: 'text',
      isActive: true
    }
  });
</script>

This approach allows mixing static and conditional class names.


Binding Inline Styles

To apply inline styles directly, use v-bind:style or :style. You can pass an object or an array of style objects.

Binding Styles with an Object

Example:

<div id="app">
  <p :style="{ color: textColor, fontSize: fontSize + 'px' }">Styled Text</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      textColor: 'blue',
      fontSize: 16
    }
  });
</script>

In this example, both color and fontSize are reactive. Changing their values updates the style in real time.

Binding Styles with a Style Object

Example:

<div id="app">
  <p :style="styleObject">Inline Styled Text</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      styleObject: {
        color: 'green',
        backgroundColor: 'lightyellow',
        padding: '10px'
      }
    }
  });
</script>

This method helps keep the template cleaner by managing styles in one object.

Conclusion

In this tutorial, you learned how to use Vue.js to bind dynamic CSS classes and inline styles using v-bind:class and v-bind:style. You saw how to bind classes using different formats such as strings, objects, and arrays. You also learned how to apply inline styles directly or through a style object. These techniques allow you to control the appearance of elements based on the application's data, making your templates cleaner and easier to manage.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram