Much of the information in an interface is conveyed visually: a full room is painted a different colour, an unavailable one appears dimmed, a bar shows the occupancy, the active filter is highlighted. All of this comes down to changing CSS classes and inline styles according to the state. Technically you could do it with ordinary v-bind, concatenating strings, but that is fragile and hard to read. That is why Vue treats class and style in a special way: they accept objects and arrays, and they are combined intelligently with static values. In this lesson you will learn those syntaxes, how to bring reactive values into the CSS itself with v-bind() and how scoped styles really work. We will apply them by giving RoomCard a different look depending on its status, an occupancy bar and a theme colour per floor.

Contents

  1. Why class and style are special
  2. :class with an object
  3. :class with an array, and combinations
  4. Static and dynamic classes together
  5. Classes calculated with computed
  6. :style with an object
  7. :style with an array, automatic prefixing and multiple values
  8. Reactive CSS variables with v-bind() in <style>
  9. <style scoped> versus global styles: how scoped works
  10. Case study: RoomCard with statuses, an occupancy bar and a theme colour

  1. Why class and style are special

Imagine you want to add the full class to the card when there are no seats left. With what you know from Data Binding, you could write:

<article :class="'card' + (full ? ' full' : '') + (!room.available ? ' unavailable' : '')">

It works, but it is unreadable, it is easy to forget a space between classes and every new class makes the expression more complicated. Because manipulating classes and styles is so common, :class and :style accept objects and arrays as well as strings, and Vue takes care of turning them into the final attribute.

  1. :class with an object

The most widely used form: an object whose keys are class names and whose values decide whether they are applied:

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

const full = ref(true)
const available = ref(true)
</script>

<template>
  <article :class="{ full: full, 'room-unavailable': !available }">...</article>
  <!-- Result: <article class="full"> -->
</template>
  • The full class is applied because its value is truthy.
  • The 'room-unavailable' key goes in quotes because it contains a hyphen, which is not valid in an unquoted JavaScript property name.
  • The values are evaluated as JavaScript truthy/falsy values: 0, '', null and undefined count as false.
  • When full or available changes, the list of classes updates itself.

If the variable has the same name as the class, you can use JavaScript's property shorthand: { full } is equivalent to { full: full }.

  1. :class with an array, and combinations

You can also pass an array of class names. Each element can be a string, an expression or even an object:

<script setup>
const status = 'full'
const featured = true
</script>

<template>
  <!-- Array of strings and expressions -->
  <article :class="['card', `card--${status}`]">...</article>
  <!-- class="card card--full" -->

  <!-- Array with a ternary -->
  <article :class="['card', featured ? 'card--featured' : '']">...</article>

  <!-- Array with an object inside: cleaner than the ternary -->
  <article :class="['card', `card--${status}`, { 'card--featured': featured }]">...</article>
  <!-- class="card card--full card--featured" -->
</template>

When should you use each form?

Syntax Ideal for Example
Object Several classes that are switched on or off independently { active: floorFilter === 1, disabled: !available }
Array Classes whose name is calculated (not just whether they apply) [`card--${status}`]
Array with objects A mix of both needs [`card--${status}`, { featured }]
String A single calculated class :class="`badge--${status}`"

Classes such as card--full follow the BEM convention (Block__Element--Modifier): card is the block, bar__fill an element and --full a modifier. It is not compulsory, but it fits very well with dynamic classes because the modifier expresses precisely the state.

  1. Static and dynamic classes together

An element can have both an ordinary class attribute and a :class. Vue combines them: the static classes are always there and the dynamic ones are added or removed:

<article class="card" :class="{ 'card--full': full }">...</article>
<!-- full = false → class="card" -->
<!-- full = true  → class="card card--full" -->

This is the most readable form: what is fixed goes in class, what depends on the state in :class. (This special behaviour only exists for class and style; with other attributes, a dynamic value and a static one are not combined.)

  1. Classes calculated with computed

When the class logic grows, move it out of the template into a computed property that returns the object or the array:

import { computed } from 'vue'

const cardClasses = computed(() => ({
  'card--available': room.available && !full.value,
  'card--full': full.value,
  'card--unavailable': !room.available
}))
<article class="card" :class="cardClasses">...</article>

Advantages: the template stays clean, the presentation logic has a name and, like any computed property, it is only recalculated when full or the room changes. This pattern is the most common one in real components.

Better still, if the states are mutually exclusive (a room is either available or full or unavailable), it is usually clearer to calculate a single status and derive the class from it, as we will do in the case study.

  1. :style with an object

For inline styles, :style accepts an object whose keys are CSS properties and whose values are their values:

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

const percentage = ref(40)
const themeColor = '#f5a623'
</script>

<template>
  <div :style="{ width: percentage + '%', backgroundColor: themeColor }"></div>
  <!-- style="width: 40%; background-color: #f5a623;" -->

  <!-- Equivalent with kebab-case in quotes -->
  <div :style="{ width: `${percentage}%`, 'background-color': themeColor }"></div>
</template>
  • Properties can be written in camelCase (backgroundColor, recommended: it needs no quotes) or in kebab-case in quotes ('background-color', as in CSS).
  • Units are not added automatically: width: 40 produces neither 40px nor 40%. Always write the unit (`${percentage}%`, `${size}px`). Properties that take no unit in CSS (opacity, zIndex, flexGrow, lineHeight) accept numbers.
  • CSS custom properties work too: { '--color-accent': themeColor }.
  • As with classes, it is combined with a static style attribute: <div style="height: 8px" :style="{ width: ... }">.

6.1 Classes or inline styles?

Use classes (:class) when... Use inline styles (:style) when...
The appearance corresponds to a named state (full, active, error) The value is continuous or comes from the data (a percentage, a position, a saved colour)
You want to be able to change the design from the CSS without touching the template It is not practical to create a class for every possible value
You need pseudo-classes (:hover), media queries or complex transitions The style affects a specific, simple property

The general rule: classes by default, inline styles for numeric or calculated values. The occupancy bar (a width from 0 to 100%) is the perfect example of :style.

  1. :style with an array, automatic prefixing and multiple values

Array of style objects: Vue merges them in order; if a property is repeated, the last one wins.

const baseStyle = { height: '8px', borderRadius: '4px' }
const fillStyle = computed(() => ({ width: `${occupancyPercentage.value}%` }))
<div :style="[baseStyle, fillStyle]"></div>

Automatic prefixing: if you use a property that the browser only supports with a vendor prefix (-webkit-, -moz-...), Vue detects at runtime which one it needs and adds it. These days it is rarely needed, but it means you do not have to worry about it in :style.

Multiple values: you can give an array of values for the same property; Vue will apply the last one the browser supports:

<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
<!-- In a modern browser: style="display: flex;" -->

  1. Reactive CSS variables with v-bind() in <style>

There is a third, very powerful route: using values from the script directly in the <style> block with the v-bind() function:

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

const themeColor = ref('#f5a623')
const theme = { border: '2px' }
</script>

<template>
  <article class="card">...</article>
</template>

<style scoped>
.card {
  border: v-bind('theme.border') solid v-bind(themeColor);
}
</style>
  • v-bind(themeColor): inserts the value of the script's themeColor variable.
  • v-bind('theme.border'): for an expression containing dots or other characters, write it in quotes.
  • It is reactive: if you change themeColor.value, the border changes.

How does it do it? The compiler replaces each v-bind() with a CSS variable with a unique name (something like var(--7ba5bd90-themeColor)) and Vue sets that variable as an inline style on the component's root element (style="--7ba5bd90-themeColor: #f5a623"), updating it when the data changes. The rest of the CSS remains static and cacheable.

Compared with :style, v-bind() in CSS lets you use the value in any selector, including :hover, pseudo-elements and media queries, something impossible with inline styles:

.button:hover {
  background: v-bind(themeColor); /* impossible with :style */
}

  1. <style scoped> versus global styles: how scoped works

You have been using <style scoped> since 01-03. The time has come to understand exactly what it does.

9.1 The mechanism: data-v attributes

When a <style> block has scoped, the compiler does two things:

  1. It adds a unique attribute, such as data-v-5f3a1b2c (the code is derived from the file), to every element in the component's template.
  2. It rewrites every selector in the CSS so that it requires that attribute.
<!-- What you write -->
<template>
  <article class="card"><h2>Panal Room</h2></article>
</template>

<style scoped>
.card h2 {
  color: var(--color-honey-dark);
}
</style>
<!-- What reaches the browser -->
<article class="card" data-v-5f3a1b2c><h2 data-v-5f3a1b2c>Panal Room</h2></article>

<style>
.card h2[data-v-5f3a1b2c] {
  color: var(--color-honey-dark);
}
</style>

Because only this component's elements have data-v-5f3a1b2c, the style cannot affect any other component, even if it uses the card class. Notice that the attribute is added to the last element of the selector (h2[data-v-...]).

Important details:

  • The root element of a child component also receives the parent's attribute, so that the parent can lay it out. The child's other elements do not.
  • Content inserted with v-html does not receive the attribute, so scoped styles do not affect it (we mentioned this in 02-01).
  • scoped styles do not protect you from global ones: an h2 { ... } in main.css still affects everything.

9.2 Special selectors: :deep(), :global() and :slotted()

Sometimes you need to "step outside" the scope:

Selector What it does Example
:deep(...) Applies the style to elements of child components (or to v-html content) .card :deep(.icon) → .card[data-v-xxx] .icon
:global(...) Writes a global rule from a scoped block :global(body.modal-open) { overflow: hidden }
:slotted(...) Styles the content another component passes into a slot You will see it in Slots

Use them sparingly: every :deep() couples your component to another one's internal structure.

9.3 When to use global styles

Type of style Where to put it
Design variables (--color-honey), base typography, reset src/assets/main.css (global)
Utility classes shared by the whole application main.css or a global file imported in main.js
The appearance of a specific component <style scoped> in the component itself

A component can have two blocks at once: a <style> (global) and a <style scoped>. Even so, it is preferable to concentrate the global styles in main.css, so that you always know where to look for them. (There is an alternative to scoped called CSS Modules, with <style module>, which generates unique class names; it is less common in Vue projects and we will not use it.)

  1. Case study: RoomCard with statuses, an occupancy bar and a theme colour

10.1 The script

We are going to give RoomCard three mutually exclusive visual statuses (available, full, unavailable), an occupancy bar and a theme colour that depends on the floor. This is the complete <script setup> of src/components/RoomCard.vue (if you did exercise 1 of the previous lesson, you already had occupancyPercentage):

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { rooms } from '@/data/rooms.js'

// The card still shows the Panal Room (in module 3 it will receive it from outside)
const room = rooms.find((r) => r.id === 'panal')

// --- Formatting ---
const euroFormatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' })

function formatPrice(amount) {
  return euroFormatter.format(amount)
}

// --- Presentation ---
const imageAttributes = {
  src: `/img/rooms/${room.id}.webp`,
  alt: `Photo of the ${room.name}`,
  width: 320,
  height: 180,
  loading: 'lazy'
}
const floorPlanUrl = `/floor-plans/floor-${room.floor}.pdf`

// Each floor of the building has its own colour
const floorColors = { 1: '#f5a623', 2: '#43a047', 3: '#5c6bc0' }
const themeColor = floorColors[room.floor]

// --- Occupancy ---
const attendees = ref(0)
const notice = ref('')

const freeSeats = computed(() => room.capacity - attendees.value)
const full = computed(() => freeSeats.value === 0)
const occupancyPercentage = computed(() =>
  Math.round((attendees.value / room.capacity) * 100)
)

// --- Visual status: a single value with three mutually exclusive possibilities ---
const status = computed(() => {
  if (!room.available) return 'unavailable'
  if (full.value) return 'full'
  return 'available'
})

const statusLabels = {
  available: 'Available',
  full: 'Full',
  unavailable: 'Unavailable'
}

watch(full, (isFull) => {
  notice.value = isFull
    ? `Room full as of ${new Date().toLocaleTimeString('en-GB')}!`
    : ''
})

function addAttendee() {
  if (!full.value) attendees.value++
}

function removeAttendee() {
  if (attendees.value > 0) attendees.value--
}

onMounted(() => {
  console.log(`[RoomCard] ${room.name} ready`)
})
</script>
  • themeColor is an ordinary constant (the room does not change), but it can still be used with v-bind() in the CSS. If the room were to change in future, it would be enough to turn it into a computed property.
  • status concentrates the logic of the three statuses in a computed property. The classes, the badge and any other visual detail are derived from it, so they can never contradict each other (for example, a card marked as both full and unavailable).
  • statusLabels translates the status into text for the user. We use a lookup object instead of chained ternaries.

10.2 The template

<template>
  <article
    class="card"
    :class="`card--${status}`"
    :id="'room-' + room.id"
    :title="`${room.name}: floor ${room.floor}`"
  >
    <img v-bind="imageAttributes" class="photo" />
    <h2>{{ room.name }}</h2>
    <span class="badge" :class="`badge--${status}`">{{ statusLabels[status] }}</span>
    <p>Floor {{ room.floor }} · {{ formatPrice(room.hourlyPrice) }}/h</p>
    <p>Equipment: {{ room.equipment.join(', ') }}</p>
    <p>Attendees: {{ attendees }} / {{ room.capacity }}</p>
    <p>Free seats: <strong>{{ freeSeats }}</strong></p>

    <div
      class="bar"
      role="progressbar"
      aria-valuemin="0"
      aria-valuemax="100"
      :aria-valuenow="occupancyPercentage"
      :aria-label="`Occupancy of the ${room.name}`"
    >
      <div
        class="bar__fill"
        :class="{ 'bar__fill--high': occupancyPercentage >= 75 }"
        :style="{ width: `${occupancyPercentage}%` }"
      ></div>
    </div>

    <p class="notice">{{ notice }}</p>
    <button :disabled="attendees === 0" @click="removeAttendee">− Attendee</button>
    <button
      :disabled="!room.available || full"
      :title="room.available ? null : 'Room unavailable'"
      @click="addAttendee"
    >
      + Attendee
    </button>
    <a :href="floorPlanUrl" target="_blank" rel="noopener">Floor {{ room.floor }} plan</a>
  </article>
</template>
  • class="card" + :class="`card--${status}`": a fixed class plus a status class, which will be card--available, card--full or card--unavailable.
  • The badge replaces the old "Available / Unavailable" paragraph and now also covers the "Full" status. In module 3 it will become the StatusBadge component.
  • The bar is made up of a grey container (.bar) and a fill whose width is bound with :style to the percentage. With 3 attendees out of 8, width: 38%.
  • 'bar__fill--high' in an object: from 75% upwards the bar changes colour as a visual warning.
  • role="progressbar" and the aria-value* attributes: a screen reader will announce "Occupancy of the Panal Room, 38%". The minimum and maximum are static; the current value, dynamic.

10.3 The styles

Replace the <style scoped> of RoomCard.vue:

<style scoped>
.card {
  max-width: 320px;
  padding: 1rem 1.5rem;
  border: 2px solid v-bind(themeColor);
  border-radius: 10px;
  background: white;
  transition:
    background-color 0.3s,
    opacity 0.3s;
}

.card--full {
  background: #fff4e5;
}

.card--unavailable {
  opacity: 0.6;
  filter: grayscale(1);
}

.photo {
  display: block;
  width: 100%;
  height: auto;
  border-radius: 6px;
  background: var(--color-background);
}

.badge {
  display: inline-block;
  padding: 0.1rem 0.6rem;
  border-radius: 999px;
  font-size: 0.8rem;
  font-weight: bold;
}

.badge--available {
  background: #e8f5e9;
  color: #1b5e20;
}

.badge--full {
  background: #fff3e0;
  color: #e65100;
}

.badge--unavailable {
  background: #eeeeee;
  color: #616161;
}

.bar {
  height: 8px;
  border-radius: 4px;
  background: #eeeeee;
  overflow: hidden; /* clips the fill to the rounded corners */
}

.bar__fill {
  height: 100%;
  background: v-bind(themeColor);
  transition: width 0.3s ease; /* the width changes smoothly */
}

.bar__fill--high {
  background: #e53935;
}

.notice {
  min-height: 1.5em;
  color: #b00020;
  font-weight: bold;
}
</style>
  • v-bind(themeColor) colours the border and the bar's fill with the floor's colour (honey for floor 1).
  • transition (ordinary CSS) smooths out the changes in width and background. Vue's own transitions for elements that appear and disappear are covered in Transitions and Animations.
  • The order matters: .bar__fill--high goes after .bar__fill so that its background takes precedence (both selectors have the same specificity).

Try the card out: add attendees and you will see the bar grow and turn red at 75% (6 out of 8), and the card will change its background and badge when it becomes full. Temporarily change the room to 'enjambre' to see the unavailable status (dimmed and in greyscale: the grayscale filter even removes floor 3's violet) and to 'nectar' to see floor 2's green. Inspect the <article> element in the browser: you will see the data-v-... attribute and, in its style, the CSS variable generated by v-bind(themeColor).

10.4 Highlighting the active filter in App.vue

Apply what you have learnt to the catalogue's floor buttons in App.vue as well:

<p>
  <button class="button" :class="{ 'button--active': floorFilter === null }" @click="floorFilter = null">
    All
  </button>
  <button class="button" :class="{ 'button--active': floorFilter === 1 }" @click="floorFilter = 1">
    Floor 1
  </button>
  <button class="button" :class="{ 'button--active': floorFilter === 2 }" @click="floorFilter = 2">
    Floor 2
  </button>
  <button class="button" :class="{ 'button--active': floorFilter === 3 }" @click="floorFilter = 3">
    Floor 3
  </button>
</p>
/* In the <style scoped> of App.vue */
.button--active {
  outline: 3px solid var(--color-text);
  outline-offset: 2px;
}

Four almost identical buttons repeated by hand are crying out for a loop: we will solve this with v-for in List Rendering.

Common Mistakes and Tips

  • Forgetting the quotes around keys with a hyphen. { room-unavailable: ... } is a syntax error; write { 'room-unavailable': ... }.
  • Forgetting the unit in :style. { width: percentage } has no visible effect; write `${percentage}%`.
  • Putting the fixed classes in :class as well. It works, but it mixes the static with the dynamic. Leave the fixed ones in class.
  • Using :style for named states. If you write :style="{ opacity: available ? 1 : 0.6 }", the design is trapped in the template. A --unavailable class is more maintainable.
  • Expecting scoped to style the inside of a child component or v-html content. It only reaches its own elements and the root of its children. Use :deep() with care.
  • Overusing :deep() and :global(). They break the isolation that scoped provides.
  • Tip: when several visual details depend on the same state, calculate a single status with a computed property and derive classes, texts and icons from it. You will avoid impossible combinations.

Exercises

Exercise 1. In App.vue, make the .selection section appear dimmed (class selection--unavailable) when the selected room is unavailable, and make the estimated price appear in red (class price--high) when it is more than €100. Use static and dynamic classes combined.

Exercise 2. In RoomCard.vue, make the theme colour editable: add an <input type="color"> bound with v-model to a themeColor ref (initialised with the floor's colour) and check that the border and the bar change live. What do you have to change in the script?

Exercise 3. State which class attribute and which style attribute result from this markup when status = 'full', featured = false and percentage = 50:

<div
  class="card"
  :class="[`card--${status}`, { featured }]"
  style="height: 8px"
  :style="[{ width: percentage + '%' }, { width: '100%', color: 'red' }]"
></div>

Solutions

Solution 1.

<section class="selection" :class="{ 'selection--unavailable': !selectedRoom.available }">
  <!-- ... -->
  · Estimated price:
  <strong class="price" :class="{ 'price--high': estimatedPrice > 100 }">
    {{ formatPrice(estimatedPrice) }}
  </strong>
  <!-- ... -->
</section>
.selection--unavailable {
  opacity: 0.6;
}

.price--high {
  color: #c62828;
}

estimatedPrice is a computed property: in the template it is compared without .value. With the Néctar Room (€35/h) and 3 hours, €105 → red.

Solution 2.

// Before: const themeColor = floorColors[room.floor]
const themeColor = ref(floorColors[room.floor])
<label>
  Theme colour
  <input v-model="themeColor" type="color" />
</label>

You only need to turn themeColor into a ref to make it reactive; the CSS does not change, because v-bind(themeColor) unwraps the ref automatically and updates the CSS variable every time it changes. With the original constant, the colour picker would change... nothing: there would be no reactivity (and v-model on a constant would give an error).

Solution 3.

<div class="card card--full" style="height: 8px; width: 100%; color: red;"></div>
  • Classes: card (static) + card--full (array); featured is not added because its value is false.
  • Styles: the static height: 8px is combined with the array of objects; in the array, the second width (100%) replaces the first (50%) because the last one wins.

Conclusion

:class and :style are special bindings that accept objects (keys that are switched on according to a condition), arrays (calculated names, which can be combined with objects) and strings, and that are combined with the static class and style attributes. For non-trivial logic, a computed property that returns the classes keeps the template clean. In :style, properties go in camelCase or in quoted kebab-case, units are explicit and Vue adds prefixes when needed. With v-bind() inside <style> you bring reactive values into the CSS through CSS variables, and you now know that scoped works by adding data-v-* attributes and rewriting the selectors, with :deep() as an escape hatch. RoomCard now shows its status with classes and a badge, an occupancy bar with :style and its floor's colour, and the filters in App.vue highlight the active one.

Classes have let us change the appearance of elements according to the state, but sometimes what needs deciding is whether an element exists at all: the "Loading rooms…" message, the error, the room-full notice. In the next lesson, Conditional Rendering, we will replace the catalogue's nested ternaries with v-if, v-else-if and v-else.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved