TExcelTAD
Home › Vue › Vue CSS Binding

Vue CSS Binding

Changing how something looks based on data is one of the most common UI tasks: highlight the selected row, colour an error red, grow a progress bar. Because class and style are attributes, you could bind them with v-bind like any other — but building class strings by hand is tedious. Vue gives :class and :style extra powers: they accept objects and arrays.

Class binding with an object

Each key is a class name; the class is added when the value is truthy.

html · try it yourself
<style>
  .task { padding: 6px 10px; margin: 4px 0; border-left: 4px solid #ccc; cursor: pointer; }
  .done { text-decoration: line-through; color: #888; }
  .urgent { border-left-color: #dc2626; font-weight: bold; }
</style>

<div id="app">
  <div v-for="t in tasks" :key="t.text" class="task"
       :class="{ done: t.done, urgent: t.urgent && !t.done }"
       @click="t.done = !t.done">
    {{ t.text }}
  </div>
  <p><small>Click a task to toggle it.</small></p>
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({
      tasks: [
        { text: 'Pay electricity bill', done: false, urgent: true },
        { text: 'Water the plants', done: true, urgent: false },
        { text: 'Read a chapter', done: false, urgent: false }
      ]
    })
  }).mount('#app');
</script>

A static class="task" and a bound :class can live on the same element — Vue merges them.

Class binding with an array

An array lists class names, which may come from data. You can mix in conditional objects or ternaries:

html · try it yourself
<style>
  .btn { padding: 8px 14px; border: none; border-radius: 6px; color: white; margin: 4px; }
  .primary { background: #42b883; } .danger { background: #dc2626; }
  .large { font-size: 18px; } .round { border-radius: 999px; }
</style>

<div id="app">
  <p>
    <select v-model="variant"><option>primary</option><option>danger</option></select>
    <label><input type="checkbox" v-model="large"> large</label>
    <label><input type="checkbox" v-model="round"> round</label>
  </p>
  <button class="btn" :class="[variant, { large, round }]">Preview button</button>
  <p>Classes: <code>btn {{ [variant, large ? 'large' : '', round ? 'round' : ''].join(' ') }}</code></p>
</div>

<script type="module">
  import { createApp } from 'vue';
  createApp({ data: () => ({ variant: 'primary', large: false, round: false }) }).mount('#app');
</script>

{ large, round } is ES shorthand for { large: large, round: round }.

Using a computed class object

When the conditions get long, move them out of the template into a computed property:

js
computed: {
  inputClasses() {
    return {
      invalid: this.touched && !this.isValid,
      valid: this.touched && this.isValid,
      disabled: this.loading
    };
  }
}
html
<input :class="inputClasses">

Style binding

:style takes an object of CSS properties. Write property names in camelCase (fontSize) or as quoted kebab-case ('font-size'). Numbers need units where CSS requires them.

html · try it yourself
<style>
  .track { width: 260px; height: 18px; background: #e5e7eb; border-radius: 9px; overflow: hidden; }
  .bar { height: 100%; transition: width .3s, background .3s; }
</style>

<div id="app">
  <p>Upload progress: {{ progress }}%</p>
  <div class="track">
    <div class="bar" :style="{ width: progress + '%', background: barColor }"></div>
  </div>
  <p>
    <button @click="progress = Math.max(0, progress - 10)">−10</button>
    <button @click="progress = Math.min(100, progress + 10)">+10</button>
  </p>
  <p :style="{ fontSize: size + 'px', color: progress === 100 ? '#16a34a' : 'inherit' }">
    {{ progress === 100 ? 'Done!' : 'Uploading…' }}
  </p>
  <input type="range" min="12" max="32" v-model.number="size"> text size
</div>

<script type="module">
  import { createApp } from 'vue';

  createApp({
    data: () => ({ progress: 40, size: 16 }),
    computed: {
      barColor() {
        if (this.progress < 30) return '#dc2626';
        if (this.progress < 70) return '#f59e0b';
        return '#42b883';
      }
    }
  }).mount('#app');
</script>

Quick reference

Syntax Result
:class="{ active: isActive }" class="active" when isActive is truthy
:class="[a, b]" classes named by the values of a and b
:class="[a, { b: cond }]" a always, b only when cond is truthy
:style="{ color: c, fontSize: s + 'px' }" inline styles from data
:style="[baseStyles, overrides]" several style objects merged, later ones win

Tip: Prefer :class over :style when you can. Classes keep the look in your CSS file, are easier to theme, and work with media queries and :hover, which inline styles cannot express.

Note: You can bind CSS custom properties, too: :style="{ '--accent': color }", then use var(--accent) in your stylesheet. In Single-File Components, v-bind() can even be used inside <style>.

Test yourself

What does :class="{ active: isActive }" render when isActive is false?

  1. class="active"
  2. class="false"
  3. No active class
  4. An error

An element has both class="card" and :class="{ selected: true }". What is the result?

  1. class="selected"
  2. class="card selected"
  3. class="card"
  4. Vue reports a duplicate attribute

How do you write the CSS property background-color in a :style object?

  1. background-color: c (unquoted)
  2. backgroundColor: c or 'background-color': c
  3. bgColor: c
  4. background_color: c