CSS transition classes help make elements change smoothly on your webpage. They add nice animations when things appear, disappear, or change.
0
0
CSS transition classes in Vue
Introduction
When you want a button to fade in or out on click.
When showing or hiding a menu with a sliding effect.
When changing the color or size of an element smoothly.
When animating a list item entering or leaving the page.
When you want to improve user experience with gentle visual feedback.
Syntax
Vue
<transition enter-active-class="enter-active" enter-from-class="enter-from" enter-to-class="enter-to" leave-active-class="leave-active" leave-from-class="leave-from" leave-to-class="leave-to" > <!-- Your element here --> </transition>
The <transition> tag wraps the element you want to animate.
Each class controls a stage of the animation: start, active, and end.
Examples
This example fades in the
div when show is true.Vue
<transition enter-active-class="fade-enter-active" enter-from-class="fade-enter-from" enter-to-class="fade-enter-to"> <div v-if="show">Hello</div> </transition>
This example slides out the
div when show becomes false.Vue
<transition leave-active-class="slide-leave-active" leave-from-class="slide-leave-from" leave-to-class="slide-leave-to"> <div v-if="show">Goodbye</div> </transition>
Sample Program
This Vue component shows a button that toggles a colored box. The box fades in when it appears and fades out when it disappears using CSS transition classes.
Vue
<template> <button @click="toggle">Toggle Box</button> <transition enter-active-class="fade-enter-active" enter-from-class="fade-enter-from" enter-to-class="fade-enter-to" leave-active-class="fade-leave-active" leave-from-class="fade-leave-from" leave-to-class="fade-leave-to" > <div v-if="visible" class="box">I fade in and out!</div> </transition> </template> <script setup> import { ref } from 'vue' const visible = ref(false) function toggle() { visible.value = !visible.value } </script> <style scoped> .box { width: 150px; height: 150px; background-color: #42b983; color: white; display: flex; align-items: center; justify-content: center; border-radius: 0.5rem; user-select: none; } .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>
OutputSuccess
Important Notes
Always define both enter and leave classes for smooth animations.
Use scoped styles to avoid affecting other parts of your app.
Test your transitions in different browsers to ensure consistency.
Summary
CSS transition classes in Vue help animate elements smoothly.
Use the <transition> wrapper with specific class names for each animation stage.
This improves user experience by making changes feel natural and gentle.