Vue CSS Binding

Vue CSS Binding

Dynamic styling is a crucial part of building interactive user interfaces.

Vue allows you to dynamically bind CSS classes and inline styles to your HTML elements.

This is achieved by using the v-bind directive (or its shorthand :) on the class and style attributes.


Binding Classes with Object Syntax

You can pass a JavaScript object to :class to dynamically toggle classes.

The key is the class name you want to apply, and the value is a boolean condition.

If the boolean condition is true, the class is added. If false, it is removed.

Object Syntax Example:

<div :class="{ active: isActive }">
  I am active!
</div>

Binding Classes with Array Syntax

You can also pass an array to :class to apply multiple classes at the same time.

This is useful when you have class names stored directly as strings inside your data variables.

Array Syntax Example:

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

Binding Inline Styles

Binding inline styles works very similarly to binding classes.

You bind to the style attribute using :style and pass an object.

CSS properties should be written in camelCase (e.g., fontSize instead of font-size) within the JavaScript object.

Inline Style Example:

<div :style="{ color: activeColor, fontSize: fontSize + 'px' }">
  Inline styling is easy!
</div>

Exercise 1 of 2

?

When using the object syntax for :class, what does the boolean value dictate?

Exercise 2 of 2

?

How should CSS properties with hyphens be written when passing them to :style as a JavaScript object?