In this tutorial we'll create a cross-browser 3D flipping card only using css3. The user will be able to flip a card and reveal its reverse side on hover or switch sides programmatically using JavaScript.
Here's an example illustrating the use of this css3 technique :
HTML Markup :
The html structure is simple, each card have a front and a back side, wrapped inside a container :
<div class="flipcard h">
<div class="front">
This is the front side
</div>
<div class="back">
This is the back side
</div>
</div>
The div with class name '
flipcard' will be the main container, inside it we will place two divs representing the two sides of the card (front and back), these two divs will actually flip when the parent div is hovered.
Just add a class named '
v' or '
h' to the main div to define the flipping direction:
horizontal or
vertical.
CSS Code :
.flipcard {
position: relative;
width: 220px;
height: 160px;
perspective: 500px;
}
.flipcard.v:hover .front, .flipcard.v.flip .front{
transform: rotateX(180deg);
}
.flipcard.v:hover .back, .flipcard.v.flip .back{
transform: rotateX(0deg);
}
.flipcard.v .back{
transform: rotateX(-180deg);
}
.flipcard.h:hover .front, .flipcard.h.flip .front{
transform: rotateY(180deg);
}
.flipcard.h:hover .back, .flipcard.h.flip .back{
transform: rotateY(0deg);
}
.flipcard.h .back{
transform: rotateY(-180deg);
}
.flipcard .front, .flipcard .back
{
position:absolute;
width: 100%;
height: 100%;
box-sizing: border-box;
transition: all 0.5s ease-in;
color: white;
background-color: #000;
padding: 10px;
backface-visibility: hidden;
}
When the main div is hovered, the two inside divs will be rotated 180° with the css3 ‘
transform’ property. The flip duration will be 0.5 second for this example.
The front and back divs have an absolute position, they will be superposed and the back side (div) will be rotated initially and will use the css3 '
backface-visibility' property to hide its backside (which became front after the initial rotation).
Programmatically flip a card :
To flip one or many cards programmatically via a button click or another javascript event, just add/remove the class 'flip' to their main div.
here’s the JavaScript line to do that :
document.querySelector('#cardId').classList.toggle('flip');
// or using jQuery
// $("#cardId").toggleClass("flip");
Browser Support
This technique rely on CSS3, it has been tested on IE10, IE11, Firefox, Google chrome and should work on most modern browsers.
Feel free to comment if you have any question or improvement.
Chtiwi Malek on Google+About the author :
Malek Chtiwi is the man behind Codicode.com
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.