Learn Vue.js · 12/13

Styling and Animations

9 min read

Creating functional components is only half the battle in modern web development. If an application looks like it was built in 1998 and elements snap in and out of existence like malfunctioning holograms, users will run away faster than you can say npm run dev.

In this guide, we cover how Vue handles styling and how to breathe life into your interfaces using Vue’s built-in animation components.


1. Scoped vs Global CSS in Vue Components

The Problem

In standard web development, CSS is entirely global. If you write .button { background: blue; } in one file, every single element with the class button across your entire website turns blue. In a large project with hundreds of components, this leads to class name collisions, unpredictable style overrides, and developers aggressively appending !important to everything just to make it work. Global CSS can quickly turn into a zombie outbreak—one infected file spreads layout chaos everywhere.

The Definition

Global CSS is styling that applies to the entire application.
Scoped CSS is a Vue Single-File Component (SFC) feature that encapsulates styling so it only applies to the HTML elements inside that specific component file.

How Scoped CSS Solves It

By simply adding the scoped attribute to your <style> tag, Vue ensures that the CSS written inside will not leak out and affect other components, even if they use the exact same class names.

html
<template>
  <button class="submit-btn">Click Me</button>
</template>

<!-- 🌍 Global CSS: Affects every .submit-btn in the app -->
<style>
.submit-btn {
  color: red;
}
</style>

<!-- 🔒 Scoped CSS: Affects ONLY the .submit-btn in this specific file -->
<style scoped>
.submit-btn {
  background-color: blue;
  border-radius: 4px;
}
</style>

Under the Hood

Vue is not using magic. When you compile your Vue application, PostCSS processes the scoped blocks. It dynamically generates a unique custom data attribute (like data-v-7ba5bd90) and attaches it to your component's HTML tags.

It then automatically rewrites your CSS selectors to target that specific attribute:

What you wrote:

css
.submit-btn { background-color: blue; }

What the browser actually gets:

css
.submit-btn[data-v-7ba5bd90] { background-color: blue; }

Industry Practice

  • Use Scoped CSS for almost all component-specific styles.
  • Use Global CSS strictly for base layout resets, typography rules, or generic utility classes (which is why utility frameworks like Tailwind CSS are so popular in Vue projects).

2. Dynamic Class and Inline Style Bindings

The Problem

Static HTML is boring. When a user types an invalid email, the input border needs to turn red. When a file finishes uploading, a progress bar needs to expand to 100%. Standard HTML class and style attributes are hardcoded strings; they cannot react to JavaScript variables or application state changes natively.

The Definition

Vue provides special binding syntax (:class and :style) that allows you to link CSS classes and inline CSS rules directly to JavaScript expressions and reactive variables.

How It Solves It

By placing a colon : before the attribute (shorthand for v-bind:), Vue knows to evaluate the content as JavaScript rather than a plain string.

Imagine you are building a smart home dashboard. You have a component for a lightbulb. You need the UI to reflect whether the light is on or off.

Object Syntax for Classes (Most Frequently Used)

You pass an object to :class where the key is the class name, and the value is a boolean condition. If the condition evaluates to true, the class is added. If false, it is removed.

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

const isLightOn = ref(false)
const hasError = ref(false)
</script>

<template>
  <!-- standard class and dynamic class can safely co-exist -->
  <div 
    class="lightbulb-base" 
    :class="{ 'glow-yellow': isLightOn, 'blink-red': hasError }"
  >
    💡 Lightbulb
  </div>

  <button @click="isLightOn = !isLightOn">Toggle Switch</button>
</template>

<style scoped>
.lightbulb-base { padding: 20px; border: 1px solid gray; }
.glow-yellow { background-color: yellow; box-shadow: 0 0 15px yellow; }
.blink-red { border-color: red; animation: blink 1s infinite; }
</style>

Binding Inline Styles

Sometimes classes aren't enough, especially when dealing with exact, highly variable numeric values (like an X/Y coordinate for a dragging element, or a percentage for a progress bar).

For inline styles, you bind an object where the keys are the CSS property names (written in camelCase) and the values are the dynamic variables.

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

const progress = ref(45) // e.g., 45% downloaded
</script>

<template>
  <div class="progress-container">
    <div 
      class="progress-fill" 
      :style="{ width: progress + '%', backgroundColor: progress > 80 ? 'green' : 'blue' }"
    ></div>
  </div>
</template>

Industry Practice

  • Always prefer Class Binding over Style Binding. Managing logic through CSS classes keeps your styles cleanly separated in your stylesheet.
  • Reserve Style Binding only for values that are impossible to predict and write classes for (like a user-defined custom color hex code from a database, or dynamic widths based on scroll position).

3. Adding Polish with Vue's Built-in Transition Component

The Problem

When you use a v-if or v-show directive to toggle an element, Vue immediately inserts or removes the element from the Document Object Model (DOM). For the user, this results in a sudden, harsh snap. A modal window instantly popping into existence feels jarring, like someone aggressively teleporting into your living room.

The Definition

<Transition> is a built-in Vue wrapper component that does not render a DOM element itself. Instead, it applies specific CSS classes to the element inside it at precisely timed moments when that element is entering or leaving the DOM.

How It Solves It

By wrapping your element in <Transition name="fade">, Vue listens for the element's insertion/removal. Before removing the element, Vue pauses, applies a sequence of CSS classes, waits for your CSS animations to complete, and then safely deletes the element.

The 6 Transition Classes

When you use <Transition name="fade">, Vue looks for these 6 CSS classes in your stylesheet:

Entering (Fading In):

  1. fade-enter-from: The starting state (e.g., opacity 0).
  2. fade-enter-active: The transition duration and easing (e.g., transition opacity 0.5s).
  3. fade-enter-to: The ending state (e.g., opacity 1).

Leaving (Fading Out):
4. fade-leave-from: The starting state (e.g., opacity 1).
5. fade-leave-active: The transition duration and easing.
6. fade-leave-to: The ending state (e.g., opacity 0).

Note: In industry practice, enter-from and leave-to usually share the exact same CSS rules (e.g., both are opacity 0). Same goes for the active classes.

Example: Smooth Modal Overlay

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

const showModal = ref(false)
</script>

<template>
  <button @click="showModal = true">Show Modal</button>

  <!-- Wrap the conditionally rendered element -->
  <Transition name="slide-fade">
    <div v-if="showModal" class="modal">
      <h2>Hello!</h2>
      <button @click="showModal = false">Close</button>
    </div>
  </Transition>
</template>

<style scoped>
.modal {
  position: fixed;
  top: 20%;
  left: 50%;
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

/* 1. Declare transition timing & easing */
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease-out;
}

/* 2. Declare start state (enter) and end state (leave) */
.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-20px); /* slide up */
  opacity: 0;                   /* invisible */
}
</style>

Under the Hood

Vue uses JavaScript's requestAnimationFrame and event listeners (like transitionend and animationend) on the element. When you trigger v-if="false", Vue intercepts the destruction of the element, adds .slide-fade-leave-active, waits for the transitionend event to fire, and finally unmounts the component from the DOM entirely.


4. Animating Lists with TransitionGroup

The Problem

The <Transition> component is strictly monogamous—it only works with a single root element inside it. If you try to wrap a list of items generated by v-for, Vue will throw an error.
Furthermore, when you add or remove an item from the middle of a list, the surrounding items instantly snap into their new positions, which again feels unpolished.

The Definition

<TransitionGroup> is a built-in Vue component designed specifically for animating elements rendered in a v-for list. Unlike <Transition>, it actually renders a wrapper HTML element (like a <ul> or <div>) and supports a special -move class to animate items smoothly shifting around.

How It Solves It

<TransitionGroup> applies the same 6 enter/leave classes to individual items as they are added or removed from the array. Additionally, it tracks the position of every item. If an item is forced to move because another item was added or deleted, it applies a move class to glide the element to its new coordinates.

Crucial Requirement: Every item inside a <TransitionGroup> absolutely must have a unique key attribute (:key="item.id"). Without a key, Vue panics like a substitute teacher who lost the seating chart—it won't know which element went where, resulting in broken animations.

Example: A Dynamic To-Do List

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

const items = ref([
  { id: 1, text: 'Learn Vue' },
  { id: 2, text: 'Master Transitions' },
  { id: 3, text: 'Get Hired' }
])

function removeItem(idToRemove) {
  items.value = items.value.filter(item => item.id !== idToRemove)
}

function addItem() {
  const newId = Math.max(...items.value.map(i => i.id), 0) + 1;
  // Insert at a random index to see the move animation!
  const randomIndex = Math.floor(Math.random() * (items.value.length + 1))
  items.value.splice(randomIndex, 0, { id: newId, text: `New Task ${newId}` })
}
</script>

<template>
  <button @click="addItem">Add Random Item</button>

  <!-- "tag" tells Vue what HTML element to render the group as -->
  <TransitionGroup name="list" tag="ul" class="todo-list">
    <li v-for="item in items" :key="item.id" @click="removeItem(item.id)">
      {{ item.text }} (Click to remove)
    </li>
  </TransitionGroup>
</template>

<style scoped>
.todo-list {
  list-style-type: none;
  padding: 0;
}
li {
  padding: 10px;
  margin-bottom: 5px;
  background: #f4f4f4;
  cursor: pointer;
  border-radius: 4px;
}

/* 1. Enter/Leave transition timings */
.list-enter-active,
.list-leave-active {
  transition: all 0.4s ease;
}

/* 2. Enter/Leave start and end states */
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

/* 3. Smoothly animate items changing position! */
.list-move {
  transition: transform 0.4s ease;
}

/* 4. Ensure leaving items don't take up space while animating */
.list-leave-active {
  position: absolute;
}
</style>

Under the Hood (The FLIP Technique)

For the .list-move class, Vue uses a rendering technique called FLIP (First, Last, Invert, Play).

  1. First: Vue calculates where the element is initially.
  2. Last: Vue calculates exactly where the element will end up after the DOM update.
  3. Invert: Vue instantly moves the element to its Last position, but uses a CSS transform to visually push it backwards so it looks like it's still in the First position.
  4. Play: Vue triggers the .list-move CSS transition and removes the transform, causing the browser to animate the element gliding gracefully to its new home.

Industry Practice

  • Use <TransitionGroup> for dynamic grids, filtering a product list, or rearranging drag-and-drop items.
  • Rule of thumb for lists: Always include position: absolute on the leave-active class. If you don't, the item leaving the list will hold onto its space in the DOM until the animation finishes, preventing the remaining items from gliding up smoothly.

📚 References & Further Reading

Challenge

You are tasked with building a dynamic and animated To-Do list application using a single Vue component. Your goal is to apply your knowledge of scoped styling, dynamic class bindings, and Vue's transition components to create a polished user experience.

Requirements:

  1. Component Logic (<script>):

    • Implement the addTask function to add a new task object to the tasks array. Each task needs a unique id.
    • Implement the removeTask function to filter out a specific task from the array.
    • Implement the shuffleTasks function to randomize the order of the tasks array.
    • Create a function that can be called from the template to toggle the completed boolean property of a specific task.
  2. Template (<template>):

    • Render the list of tasks inside a <TransitionGroup> component. The transition group must render a <ul> element and use list as its transition name.
    • Each task should be rendered as an <li> element. Crucially, ensure each li has a unique :key attribute.
    • Inside each <li>, display the task's text. Also include a button to trigger removeTask and another clickable element to toggle the task's completion status.
    • Use a dynamic :class binding on each <li> to apply a completed class when the task's completed property is true.
  3. Styling (<style scoped>):

    • All your styles must be inside the <style scoped> block.
    • Define a .completed class that changes the appearance of a task item (e.g., text-decoration: line-through;, opacity: 0.6;).
    • Define all necessary CSS classes for the list transition to achieve the following effects:
      • Enter: Items should fade in from 0 to 1 opacity and slide up from 30px below.
      • Leave: Items should fade out to 0 opacity and scale down to 0.6.
      • Move: Use the list-move class to create a smooth transform transition when items are shuffled.
      • Important: To ensure the remaining items animate smoothly into place when an item is removed, you must apply position: absolute; and width: 100%; to the list-leave-active class.

Expected result

When you have successfully completed the challenge, your component should function as follows:

  • Initial State: A list of three tasks is displayed. The first task appears visually distinct (e.g., with a line-through) because it is marked as 'completed'.
  • Adding Tasks: Clicking the "Add Task" button adds a new, uncompleted task to the end of the list. The new item smoothly fades and slides into view.
  • Removing Tasks: Clicking the remove button next to a task causes it to fade and scale down. Simultaneously, any items below it smoothly slide up to fill the empty space.
  • Toggling Completion: Clicking on a task's li element switches its completed state. This change must be instantly reflected in its styling due to the dynamic :class binding.
  • Shuffling: Clicking the "Shuffle Tasks" button reorders the list. All items gracefully glide to their new positions without any abrupt jumps.
  • Style Encapsulation: All styling for the component, including the transition effects, is properly scoped and does not affect any other elements on the page.
html

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.