Class and style bindings

Beginner · 6 min

Vue's object and array syntax for binding class and style, how bound classes merge with static ones, and when to reach for a class instead of an inline style.

Before thisText interpolation and attribute binding

Atom Jar | AI for Everyone · 57 min · from 26:23

Class and style bindings

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Atom Jar | AI for EveryoneReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `:class` and `:style` accept objects and arrays as well as strings, because building class lists and style strings by concatenation is error-prone.
  • In object syntax, `:class="{ active: isActive }"` adds the `active` class whenever `isActive` is truthy and removes it otherwise. Several keys can be toggled independently.
  • A bound `:class` merges with a static `class` on the same element rather than replacing it.
  • Array syntax lists classes to apply, and an array can mix plain class names with objects for the conditional ones.
  • `:style` takes an object of CSS properties in camelCase or quoted kebab-case, adds vendor prefixes when a browser needs them, and can set CSS custom properties such as `'--accent'`.
  • Prefer toggling a class for anything a stylesheet can describe. Save inline `:style` for values that are truly computed at runtime, like a user-chosen colour or a measured width.

Why class and style get special treatment

You already know v-bind can bind any attribute to an expression. Nothing stops you from writing this:

<button :class="'btn' + (primary ? ' btn-primary' : '') + (busy ? ' is-busy' : '')">
  Save
</button>

It works, and it is miserable. Every class needs its own ternary, the spaces between names are easy to get wrong, and the intent (“this button is primary, and maybe busy”) is buried in string plumbing. Inline styles are worse, since a style string is a mini-language of its own with colons and semicolons.

Since class and style are the two attributes nearly every interactive element toggles, Vue gives them an upgrade. When bound with v-bind, they accept objects and arrays as well as strings, and Vue does the string assembly.

Object syntax for classes

The most common form maps class names to conditions:

<script setup>
import { ref } from 'vue'

const inStock = ref(false)
const selected = ref(true)
</script>

<template>
  <button
    class="button"
    :class="{ 'disabled-button': !inStock, selected }"
    :disabled="!inStock"
  >
    Add to cart
  </button>
</template>

Each key is a class name, applied when its value is truthy. Class names containing hyphens need quotes, because they are object keys. selected uses the JavaScript property shorthand for selected: selected. With these values the button renders as class="button disabled-button selected".

Notice that the static class="button" survived. A bound :class is merged with a plain class on the same element, so the classes an element always has go in the static attribute and only the changing ones go in the binding.

When the object grows, move it into the script. A computed property is the natural home, because it recalculates only when the state it reads changes:

<script setup>
import { computed } from 'vue'

const props = defineProps(['variant', 'busy', 'disabled'])

const buttonClasses = computed(() => ({
  [`btn-${props.variant}`]: true,
  'is-busy': props.busy,
  'is-disabled': props.disabled,
}))
</script>

<template>
  <button class="btn" :class="buttonClasses"><slot /></button>
</template>

defineProps is formally introduced in components and props; here it is just a source of values.

Array syntax

An array lists classes to apply. Strings are applied as they are, and an object inside the array handles the conditional entries:

<div :class="[sizeClass, themeClass, { 'is-open': open }]"></div>

Arrays are handy when class names themselves come from data, such as a size or theme prop, and objects are handy for on/off toggles. Mixing them lets you have both without falling back to string concatenation.

Classes on components

Put :class on a child component and the classes land on that component’s root element, merged with whatever classes the root already has. A component with several root elements has no single element to put them on, so it must say where they go. That behaviour belongs to a broader mechanism covered in fallthrough attributes.

Binding inline styles

:style takes an object of CSS properties. Keys can be camelCase, matching the DOM’s element.style API, or kebab-case in quotes, matching CSS:

<script setup>
import { ref } from 'vue'

const color = ref('green')
const progress = ref(64)
</script>

<template>
  <div class="swatch" :style="{ backgroundColor: color }"></div>

  <div class="bar" :style="{ width: `${progress}%`, 'border-radius': '4px' }"></div>
</template>

Values are CSS values, so units are your job. width: 64 is ignored by the browser; width: '64%' works. React adds px to some numeric style values automatically. Vue does not.

A few more capabilities:

  • Arrays of objects merge, later objects winning: :style="[baseStyles, overrideStyles]".
  • Vendor prefixes are added automatically at runtime when the current browser needs one for a property.
  • Multiple fallback values can be given as an array, and Vue uses the last one the browser supports: { display: ['-webkit-box', '-ms-flexbox', 'flex'] }.
  • CSS custom properties can be set like any other key: :style="{ '--accent': userColor }". Then your stylesheet uses var(--accent), which keeps the actual styling in CSS while the value comes from data.

As with :class, a bound :style merges with a static style attribute on the same element.

Classes first, styles when you must

Think of classes as named switches on a control panel and inline styles as hand-adjusting a dial. Switches are predictable, documented in one place, and can drive many properties at once. A dial gives you any value but nobody else knows what you set it to.

Toggling a class keeps the visual design in the stylesheet, where it can use hover and focus states, media queries, transitions and your design tokens, none of which inline styles can express. The template only says which state the element is in. Reach for :style when the value genuinely cannot be known ahead of time: a colour the user picked, a width measured from the DOM, a position from a drag. Even then, setting a CSS custom property and letting the stylesheet consume it is often the cleaner split. The box model and the cascade explains why inline styles beat almost every stylesheet rule, which is the other reason to use them sparingly.

What the video covers

The embed is Lesson 7 of Adam Jahr’s Composition API version of Vue Mastery’s Intro to Vue 3, about six minutes in <script setup>. It turns product variants into colour swatches with :style="{ backgroundColor: variant.color }" and greys out the Add to Cart button with :class="{ disabledButton: !inStock }" alongside :disabled, a realistic pairing of the two bindings. Its focus is the object syntax. Array syntax, merging on components, units, fallback values and custom properties are covered in this lesson instead.

Where this fits

Scoped styles, CSS modules, and v-bind() inside a <style> block are the stylesheet side of the same problem, covered in styling Vue components. Next in this group is event handling and modifiers.

Check yourself

  1. 01What class attribute does `<div class="card" :class="{ selected: isSelected, 'is-empty': !items.length }">` produce when `isSelected` is true and `items` is empty?

    `class="card selected is-empty"`. The static `card` class is kept, and each object key whose value is truthy is added. `is-empty` needs quotes in the object because it contains a hyphen.

  2. 02How would you always apply a `btn` class and add `btn-primary` only when `primary` is true, using array syntax?

    `:class="['btn', { 'btn-primary': primary }]"`. Plain strings in the array are always applied, and the object inside it handles the conditional class.

  3. 03Why does `:style="{ width: size }"` with `size = 200` not set a 200-pixel width?

    Vue does not add units for you. `width: 200` is not valid CSS, so the browser ignores it. Bind a string with the unit, such as `` { width: `${size}px` } `` or `{ width: size + 'px' }`.

  4. 04A button needs a red background when a form has errors. Is `:style` or `:class` the better choice?

    `:class`, for example `:class="{ 'has-error': hasErrors }"` with the colour defined in CSS. The look stays in the stylesheet where it can use the design system's variables, hover states and media queries, and the template only records which state the button is in. Inline styles suit values that cannot be known ahead of time.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark