Step 1: Create Your HTML Elements
To get started, in your index.html file create the following containers
- Main div container that will store all your flip cards
- Div element for an individual flip card. Add a div id, so we can easily select this element on the DOM later.
- A front div and back div with the class set to “front” and “back” respectively which are nested inside your card div.
- Add the HTML inner text that you want to display on the front and the back div.
Step 2: Add CSS classes to your HTML Elements
In order to create the flip effect, we will need to add CSS to each of our newly created divs.
Make sure that you link to your CSS file in your HTML index file.
Here is a sample of what your CSS code should look like:
The div class .card will hold our front and back elements; the css below positions and styles our div card container. Most importantly, the line “transform-style: preserve-3d” is what will eventually allow us to make the flip between the front and back face of the card.
The front and back classes provide positioning and styling to our respective divs. In this example, the front div element is the default face of the card element, while the back is the reverse side of our card element.
Feel free to play around with the size, color, and other stylistic features of your flip card.
Step 3: Add an Event Listener to your Flip Card
This last step is where the magic happens! In your JS index file, we’re going to add an event listener to the card container, so that each time we click the card a flip occurs.
Before you continue, make sure your JS source file is listed in your HTML index file.
- Firstly, in your JS index file you will need to select the card div and set it equal to a const.
- Then, add an event listener to your card const that fires when a user clicks.
- Create a callback function which sets the card’s class equal to a new CSS class “flipCard” which toggles on a click. As the name suggests, the .toggle() method allows us to switch between classes — in the parentheses we pass in the name of the class that we want to toggle.
- To allow the toggle event to execute correctly, go back to your CSS file and add a new class called “.flipCard” which makes the horizontal transformation of 180 degrees, so that our card moves between the front and back elements.
And voila, there you have it — a card that flips on click! While there are many ways to create a flip effect, I found this way to be one of the easiest to understand and implement. You’re now well on your way to adding a cool flip card effect in your next project!
How To Create a Flip Card with CSS
The flip card container - set the width and height to whatever you want.
Flip Card Effect Video: https://www.youtube.com/watch?v=OV8MVmtgmoY