Skip to content

How to dynamically apply a class using Vue 2

Learn how to make Vue output a class or another depending on some condition

Say you want to apply the class background-dark to an element, if the isDark prop is true, and otherwise add the background-light.

How would you do that in Vue?

Use :class="[ isDark ? 'background-dark' : 'background-light' ]"

Here’s an example:

<template>
  <div :class="[ isDark ? 'background-dark' : 'background-light' ]">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  props: {
    isDark: Boolean
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .background-dark {
    background-color: #000;
  }
  .background-light {
    background-color: #fff;
  }
</style>

(many thanks to Adam Wathan for suggesting this to me on the Tailwind Slack)


→ Get my Vue.js 2 Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list