Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 87 ยท Template Syntax

Class and Style Binding

Bind CSS classes and inline styles in Vue 3 with object and array syntax, conditional classes, style objects, arrays of styles and automatic vendor prefixing.

Almost every interface changes its look as its state changes: a button becomes "loading", a field turns red when it is invalid, a progress bar grows. In plain JavaScript you would reach for element.classList.add() and element.style.width = ... and keep the DOM in sync by hand. In Vue you describe the look as a function of your data and let Vue do the DOM work.

class and style get special treatment in Vue. They are ordinary attributes, so v-bind works on them, but Vue extends :class and :style so that they accept objects and arrays as well as strings. This lesson shows each form, when to choose which, and how it combines with a static class attribute.

Binding classes with an object

Pass an object to :class. Each key is a class name, and the class is present when the value is truthy:

Object syntax for classes

Notice that the paragraph has a plain class="box" as well as :class="classes". Vue does not replace one with the other: it merges them, so the rendered element is class="box active" while the first checkbox is on. Static classes are never removed by a binding.

If a class name contains a hyphen, quote the key: { 'is-open': open }. Any expression works as the value, for example { danger: count > 10 }.

flowchart LR
  S["State<br/>(isActive, hasError)"] --> C["computed classes object"]
  C --> B[":class binding"]
  B --> M["Vue merges with<br/>static class attribute"]
  M --> D["class attribute in the DOM"]

State flows into an object, and Vue merges that object with the static class attribute.

Binding classes with an array

An array lists class names. Each item is added to the element, and items can be strings, objects or ternaries:

HTML
<p :class="[baseClass, isActive ? 'active' : '', { error: hasError }]">Text</p>

Empty strings, null, undefined and false are ignored, so a ternary with an empty "else" branch is fine. Arrays are handy when the class names themselves come from data, such as a size or variant prop. For a plain on/off class, an object is shorter, and a ternary inside an array is only worth it for either/or choices.

Array syntax with a variant picker

The class btn- plus the selected variant is computed from data, which an object key cannot do directly. If you build class names from strings, make sure the stylesheet actually contains them. Tools such as Tailwind scan your source for complete class names, so 'btn-' + variant would never be found by such a scanner; write the full names in your code in that case.

Classes on components

When you put class on a component tag, Vue adds it to the component's root element, again merging with whatever classes the root already has. That is explained in Fallthrough Attributes; for now, remember that class and style behave consistently on elements and components.

Binding inline styles with an object

:style takes an object whose keys are CSS properties. You may write camelCase (fontSize) or kebab-case in quotes ('font-size'); camelCase avoids the quotes:

A style object driven by a slider

Two details worth knowing:

  • Values are strings. CSS needs units, so fontSize: size would not work for a number; write size + 'px' or a template literal. (A few unitless properties such as opacity and lineHeight accept plain numbers because CSS itself does.)
  • Prefer a named object for anything long. Inline objects in the template quickly become hard to read. Put the object in a computed or a reactive and bind it: :style="boxStyle".

Auto-prefixing

When you use a CSS property that needs a vendor prefix in some browsers, Vue checks at runtime which spelling the current browser supports and uses it. You write { userSelect: 'none' } once, and Vue picks the supported form for you. Modern browsers rarely need prefixes now, but the feature costs you nothing.

Arrays of style objects

:style also accepts an array of objects, which Vue merges from left to right; later keys win:

HTML
<div :style="[baseStyle, overrideStyle]"></div>

That is useful for a shared base plus a variant, or when a component receives extra styles from its parent. You can also supply an array of values for one property, such as { display: ['-webkit-box', 'flex'] }: Vue renders the last value the browser supports.

Conditional classes, in practice

Classes usually express a state (is-open, has-error, selected) and the CSS decides what it looks like. That separation is the main reason to prefer classes over inline styles:

Use When
:class object A class is on or off depending on a condition
:class array Class names come from data, or you combine several sources
:style object The value itself is dynamic: a width in pixels, a user-picked color, a computed position
Plain class Anything that never changes

A rule of thumb: if you can name the state, use a class. If the number comes from data (a progress percentage, a drag position), use a style.

Class for state, style for numbers

The color is a state (class), the width is a measurement (style). Each does the job it suits best.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Vue do when an element has both class="box" and :class="{ active: isActive }"?

    Static and bound classes are combined. The static ones are always present; the bound ones come and go.
  2. 2. Which :class value adds the class named is-open only when open is true?

    A class name with a hyphen is not a valid bare JavaScript key, so it must be quoted. An unquoted is-open would be parsed as a subtraction.
  3. 3. You want a bar whose width follows a number in your data. What is the best binding?

    The width is a measurement that comes from data, so it belongs in an inline style. Remember to add the unit as a string.
  4. 4. With :style="[a, b]", where both objects set color, which color is rendered?

    Vue merges the style objects from left to right, so later objects override earlier ones.

Summary

  • :class accepts a string, an object ({ name: condition }), an array, or a mix of them; bound classes merge with a static class.
  • Quote class names that contain hyphens when you use the object syntax.
  • :style takes an object of CSS properties (camelCase or quoted kebab-case) whose values need units; an array merges several objects, later ones winning.
  • Vue picks the vendor-prefixed spelling a browser supports, so you write the standard property.
  • Use classes for named states and inline styles for values that come from data.

Next, show and hide whole pieces of the page in Conditional Rendering.