Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Flipping a div (part 2)

Posted on: 2013-07-15

In a previous post, we have discussed about how to flip a division. However, Javascript was involved with CSS3 while only CSS3 could have been enough. For the curious, here is the code/JsFiddle (most of the code is not from me, but I cannot find the source).

First of all, the Html structure changes a little with two divisions with the same class ("side") within 2 divisions. One is the card container and the second is card. The card will be the one animated while the card container act as a placeholder.

<div class="card-container"> 
  <div class="card"> 
    <div class="side">
      <img src="thisisanimage.png"/>
    </div> 
    <div class="side back">This is some text</div> 
  </div> 
</div> 

As for the CSS, the perspective is also set to have a 3d look of depth. This is what the card-container is for.

After, the card is assigned to have a transition of 1 second. Nothing is trigged until the card has a transformation applied, which is the case with the next CSS statement.

.card-container { 
  -webkit-perspective: 600; 
  margin-bottom: 20px; 
  position: relative; 
  width: 150px; 
}

.card { 
  position: absolute; 
  -webkit-transform-style: preserve-3d; 
  -webkit-transition: all 1s ease-in-out; width: 100%;
} 

.card:hover { 
  -webkit-transform: rotateY(180deg);
 } 
 
.card .side { 
  -webkit-backface-visibility: hidden; 
  position: absolute; width: 100%;
} 

.card .back { 
  color: #404853; 
  font-size: 14px; 
  font-weight: bold; 
  line-height: 150px; 
  text-align: center;
  -webkit-transform: rotateY(180deg); 
  background-color:yellow; 
} 

The :hover statement raise the transition to be executed (with the 1 second time). As you may have notice, the use of backface-visibility lets the rendering to not display the back of the div but instead display the other division which rotate at the same time. This create the illusion that we are seeing the back of the division, but in fact, we are showing the other division. This is possible because of the position set to absolute. This put both division over each others.