How to Use CSS Transition in Vue: Simple Guide with Examples
In Vue, you use the
<transition> component to apply CSS transitions to elements entering or leaving the DOM. Wrap the element with <transition> and define CSS classes for the transition states to create smooth animations.Syntax
The <transition> component wraps the element you want to animate. It automatically adds CSS classes during different phases: -enter-from, -enter-active, -enter-to, -leave-from, -leave-active, and -leave-to. You define CSS rules for these classes to control the animation.
Example usage:
<transition name="fade">: sets the base name for CSS classes.- Inside, the element to animate appears or disappears.
- Vue adds classes like
fade-enter-activeduring the transition.
vue
<transition name="fade"> <p v-if="show">Hello Vue!</p> </transition>
Example
This example shows a button toggling a message with a fade transition. The message smoothly appears and disappears using CSS opacity and transition properties.
vue
<template>
<div>
<button @click="show = !show">Toggle Message</button>
<transition name="fade">
<p v-if="show">This message fades in and out!</p>
</transition>
</div>
</template>
<script setup>
import { ref } from 'vue'
const show = ref(false)
</script>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
.fade-enter-to, .fade-leave-from {
opacity: 1;
}
</style>Output
A button labeled 'Toggle Message' that when clicked shows or hides a paragraph with a smooth fade effect.
Common Pitfalls
Common mistakes include:
- Not defining all required CSS classes (
-enter-from,-enter-to,-leave-from,-leave-to) causing no visible animation. - Forgetting to wrap the element inside
<transition>, so Vue won't apply transition classes. - Using
v-showinstead ofv-ifwhich only toggles visibility and may not trigger leave transitions.
vue
<!-- Wrong: No transition wrapper --> <p v-if="show">No transition here</p> <!-- Right: Wrapped in transition --> <transition name="fade"> <p v-if="show">Smooth fade</p> </transition>
Quick Reference
| Class Name | When Applied | Purpose |
|---|---|---|
| Start of enter transition | Initial state before entering (e.g., opacity: 0) | |
| During enter transition | Defines transition properties (duration, easing) | |
| End of enter transition | Final state after entering (e.g., opacity: 1) | |
| Start of leave transition | Initial state before leaving (e.g., opacity: 1) | |
| During leave transition | Defines transition properties for leaving | |
| End of leave transition | Final state after leaving (e.g., opacity: 0) |
Key Takeaways
Wrap elements with to enable CSS transitions in Vue.
Define CSS classes for enter and leave states with proper naming.
Use v-if to trigger enter and leave transitions correctly.
Ensure all transition classes (-enter-from, -enter-to, etc.) are defined for smooth animation.
Avoid using v-show if you want leave transitions to run.