简简又单单的卡片翻转动画效果

133 阅读1分钟

简简又单单的翻转卡片动画效果,仅用 CSS 就可以实现完成,实现的原理非常简单,但又比较有意思和使用

overturn-1.webp

绘制卡片

所用到的 DOM 结构如下。

<div class="container">
    <div class="front flex">front</div>
    <div class="back flex">back</div>
</div>

直观理解,front即为卡片的正面,back为卡片的背面。分别为卡片的正面与背面设定不同的颜色,以便于区分。

.front {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: red;
    transition-duration: 0.5s;
}
.back {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: blue;
    transform: rotateY(-180deg);
    transition-duration: 0.5s;
}

然而,这样并不能使正反面分离,翻转至正面时,反而会出现这种情况。

overturn-2.webp

这是由于“背面的背面”覆盖到了正面上,为解决这一问题,我们需要向frontback添加一条规则以隐藏各自的“背面”。

backface-visibility: hidden;

卡片的翻转

现在我们可以开始关注如何使卡片翻转起来了。
我们设想,当鼠标移动到卡片上时,卡片由正面翻转至背面,因此我们使卡片翻转 180°。需要注意的是,翻转的效果设置在卡片的正反面,即frontback上,而:hover则要设置在container上,否则将会出现这种情况。

overturn-3.webp

正确的做法是。

.container:hover .front {
    transform: rotateY(180deg);
}
.container:hover .back {
    transform: rotateY(0deg);
}

示例

完整的示例如下。

<html>
  <head>
    <meta charset="utf-8" />
    <title>OVERTURN</title>
  </head>
  <body>
    <div class="container">
      <div class="front flex">front</div>
      <div class="back flex">back</div>
    </div>
    <style>
      .flex {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .container {
        perspective: 500px;
        position: absolute;
        width: 100px;
        height: 100px;
        color: white;
        font-size: 28;
      }
      .container:hover .front {
        transform: rotateY(180deg);
      }
      .front {
        position: absolute;
        width: 100%;
        height: 100%;
        background-color: red;
        transition-duration: 0.5s;
        backface-visibility: hidden;
      }
      .container:hover .back {
        transform: rotateY(0deg);
      }
      .back {
        position: absolute;
        width: 100%;
        height: 100%;
        background-color: blue;
        transform: rotateY(-180deg);
        transition-duration: 0.5s;
        backface-visibility: hidden;
      }
    </style>
  </body>
</html>