Search code examples
css3dcss-transitionscss-transforms

Flip a 3D card with CSS


I'm trying to make a 3D card flipping effect with CSS like this.

3D flipping card with CSS

The difference is that I want to use only CSS to implement it.

Here is the code I tried:

/*** LESS: ***/

    .card-container {
        position: relative;
        height: 12rem;
        width: 9rem;
        perspective: 30rem;
        .card {
            position: absolute;
            width: 100%;
            height: 100%;            
            div {
                position: absolute;
                height: 100%;
                width: 100%;
            }
            .front {
                background-color: #66ccff;
            }
            .back {
                background-color: #dd8800;
                backface-visibility: hidden;
                transition: transform 1s;
                &:hover {
                    transform: rotateY(180deg);
                }
            }
        }
    }
HTML:
<div class="card-container">
  <div class="card">
    <div class="front"><span>Front</span></div>
    <div class="back"><span>Back</span></div>
  </div>
</div>

The issue is that the card doesn't flip, it snaps from back to front like this:

Flipping card effect not working

Is it possible to implement this 3d card flip on hover effect using only CSS?


Solution

  • I simplified the code to make it shorter and make the 3d card flip on hover. The card flips on the Y axis from the front face to the back face this is what it looks like:

    CSS 3D flipping card on hover

    Here is an example of a simple CSS only flipping card the flip animation is launched on hover :

    .card {
      position: relative;
      width: 50vh;
      height: 80vh;
      perspective: 500px;
      margin: 10vh auto 50vh;
    }
    
    .front,
    .back {
      position: absolute;
      width: 100%;
      height: 100%;
      transition: transform 1s;
      backface-visibility: hidden;
      transform-style: preserve-3d;
    }
    
    .front {
      background-color: #66ccff;
    }
    
    .back {
      background-color: #dd8800;
      transform: rotateY(180deg);
    }
    
    .card:hover .front {
      transform: rotateY(180deg);
    }
    
    .card:hover .back {
      transform: rotateY(360deg);
    }
    <div class="card">
      <div class="front"><span>Front</span></div>
      <div class="back"><span>Back</span></div>
    </div>

    This is what I changed in your code for the flip effect:

    • the front face wasn't rotated on th Y axis on hover
    • the hover effect was launched when the .back div was hovered. This can create flickering as that div is rotating and "disapears" at mid rotation. It's better to launch the animation when the static parent is hovered.
    • the first parent isn't really usefull so I removed it