CSS3 3D Transformations: backface-visibility

Craig Buckler

In my previous article we transformed various elements in three-dimensional space, e.g. rotating around the y-axis:

transform: rotateY(180deg);

The element is effectively reversed and the child elements show through:


Sometimes you’ll want that effect. But sometimes you won’t. Let’s create a playing card which can be flipped over on hover/focus using a 3D transformation in conjunction with a transition. Our HTML code defines the front and back of the ace of hearts:

<div class="card">
	<div class="front"><span>A♥</span> ♥ <span>A♥</span></div>
	<div class="back"></div>

In the starting state, the front is rotated 180 degrees. (Actually, I’ve used -179.9 degrees to ensure it always rotates the same way since browsers will use the shortest path):

div.card div.back
	transform: perspective(400px) rotateY(0deg);

	transform: perspective(400px) rotateY(-179.9deg);

On hover/focus, both sides are rotated clockwise around the y-axis with perspective to give the illusion of a flipping card:

div.card:hover div.back, div.card:focus div.back
	transform: perspective(400px) rotateY(179.9deg);

div.card:hover div.front, div.card:focus div.front
	transform: perspective(400px) rotateY(0deg);

Unfortunately, it doesn’t work: View the first 3D card flipping page…

The back on the card will always appear above the front because that’s the way it’s defined in the HTML. No amount of z-index manipulation shenanigans will help you.

Fortunately, there’s a simple solution. The backface-visibility (and -webkit-backface-visibility) can be assigned a value of:

  • visible — the default; the element is reversed, or
  • hidden — an element is hidden when it is reversed

We can therefore apply this to our front and back elements:

div.card div
	backface-visibility: hidden;

Success! View the second 3D card flipping page…

If you reduce the animation speed (by increasing the time), you’d discover that div.front becomes visible after it has rotated by 90 degrees and div.back becomes invisible at the same time.

When combined with transitions and animations, 2D and 3D transformations become incredibly powerful and effective. It’s too easy to go overboard with migraine-inducing effects — sometimes, less is more — but the only limit is your imagination. Please post URLs to any interesting demonstrations you create.