Class and Style Binding
Dynamically bind CSS classes and inline styles based on component state.
Binding Classes with an Object
Passing an object to :class toggles each key's class name on or off based on whether its value is truthy — a clean way to express several conditional classes at once.
<script setup>import { ref } from 'vue';const isActive = ref(true);const hasError = ref(false);</script>
<template> <div :class="{ active: isActive, error: hasError }"> Status indicator </div></template>This renders class="active" — hasError is false, so the error class is omitted, and Vue merges this with any static class attribute already on the element.
Binding Classes with an Array
An array applies each listed class, and can mix in the object syntax for conditional entries.
<template> <div :class="[baseClass, isActive ? 'active' : '']">Item</div> <div :class="[baseClass, { active: isActive }]">Item</div></template>Binding Inline Styles
:style accepts an object of camelCase CSS properties, or an array of such objects to merge.
<script setup>import { ref } from 'vue';const color = ref('red');const fontSize = ref(16);</script>
<template> <p :style="{ color: color, fontSize: fontSize + 'px' }"> Styled text </p></template>Where possible, toggle a CSS class instead of computing raw style objects — it keeps styling in your stylesheet and usually performs better for anything beyond a one-off dynamic value.
FAQs
Yes — a computed property returning an object or array works exactly like an inline expression, and is often clearer for complex conditional logic.
No for the object syntax (fontSize: '16px'), though kebab-case with quotes also works: 'font-size': '16px'.
Summary
:class and :style both accept object or array syntax for clean, declarative conditional styling. With template fundamentals covered, the next section moves into building and composing components.