Animation can be a powerful way to enhance a user experience. In this lesson, we'll walk through the creation of a card-flip animation, creating a nice visual effect when toggling between the front and back of a div meant to represent a card, like a playing card, or a flashcard. We'll create this effect using a touch of JavaScript and CSS transforms. No framework or library required.
.container { display: flex; flex-direction: column; align-items: center; width: 50vw; margin: auto; } .card { margin-top: 1rem; height: 60vh; width: 100%; position: relative; } .cardFront, .cardBack { border-radius: 0.25rem; height: 100%; padding-left: 0.5rem; padding-right: 0.5rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); width: 100%; position: absolute; backface-visibility: hidden; transition: transform 0.5s ease; } .cardBack { transform: perspective(600px) rotateY(180deg); background-color: #ebf4ff; } .cardBack.flipped { transform: perspective(600px) rotateY(0deg); } .cardFront { transform: perspective(600px) rotateY(0deg); } .cardFront.flipped { transform: perspective(600px) rotateY(-180deg); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>CSS Card Flip</title> <link rel="stylesheet" href="./styles.css" /> </head> <body> <div class="container"> <button type="button" id="flip-btn">Flip Card</button> <div class="card"> <div id="back" class="cardBack">Back</div> <div id="front" class="cardFront">Front</div> </div> </div> <script> const front = document.getElementById('front') const back = document.getElementById('back') const btn = document.getElementById('flip-btn') function handleFlip() { front.classList.toggle('flipped') back.classList.toggle('flipped') } btn.addEventListener('click', handleFlip) </script> </body> </html>