How to Create a Flip Card Using CSS

By
css
coding
ui/ux
Open in Demo.js

CSS can do various kinds of UI implementations. It improves user experience and engagement with the web applications. In this article, we are going to show how we can create a card component that can be flipped and see the content behind it. This kind of UI design can be useful for creating interactive elements, item listings, and even puzzle games. Let's see how we can create this flip card only using CSS and HTML.

Look at the following example. Try hovering on the card to flip it and see the content behind it.

Hover Me to See The Content Behind
This is The Content Behind

First, we need to create the HTML structure for the card. Since the card has two sides, we can create a parent element to contain two elements, which are the two sides of the card. And the entire card should be able to rotate. Therefore, we are going to have another fixed parent level.

<!-- card root -->
<div class="card">
  <!-- rotating inner -->
  <div class="card-inner">
    <!-- front -->
    <div class="card-side card-front">
      Front
    </div>
    <!-- back -->
    <div class="card-side card-back">
      Back
    </div>
  </div>
</div>

The top-level element should be fixed without rotating, and should hold the required space for the card to be visible. Also, to make the rotation look more real and 3D, we should provide a perspective value as well.

/* parent container */
.card {
  /* absolute sizes */
  width: 150px;
  height: 100px;
  /* rotation depth */
  perspective: 1000px;
}

Then, the inner element should be rotatable and should be relative to the side elements inside it. We can define the transition settings on this and add the hover rule to rotate when moving the pointer onto the top-level card element.

/* rotating card root */
.card-inner {
  /* get parent sizes */
  width: 100%;
  height: 100%;
  /* make cars sides in absolute positions */
  position: relative;
  /* rotation animation settings */
  transition: transform 0.5s;
  /* rotation depth */
  transform-style: preserve-3d;
}

/* while hovering the card */
.card:hover .card-inner {
  /* rotate the card inner around */
  transform: rotateY(180deg);
}

For both cards, we should set the absolute positioning. Also, make sure to disable the visibility on the backface. Therefore, while the elements are rotated around, you will not see the mirrored element as usual. Since the back card should be facing behind, make sure to rotate it initially.

.card-side {
  /* get parent sizes */
  width: 100%;
  height: 100%;
  /* place sides in absolute positions */
  position: absolute;
  /* hide back surfaces */
  backface-visibility: hidden;
  /* decorations */
  background-color: #06f;
  color: #fff;
}

/* back card should be rotated initially */
.card-back {
  transform: rotateY(180deg);
}