纯CSS制作跳动的心

1,645 阅读2分钟

这是我参与8月更文挑战的第23天,活动详情查看:8月更文挑战

问题起源

CSS不知道写啥了,兄弟们给出道题目吧

今天来写一个跳动的心给各位工友们,把你的心拿给那个她/他吧。

画心

我们先来看看长什么样子?

简略的,我们可以按照如下方法拆分“”形:(请忽略线条的曲曲折折~)

image.png

我们可以将“心形”拆分为一个正方形与两个半圆形。

为了减少DOM元素,我们可以通过:before:after两个伪元素,从而可以通过一个DIV绘制出一个完整的心形。话不多说,先看效果:

image.png

然后我们统一颜色,并进行旋转。

image.png

我们上代码:


<!DOCTYPE html>
<title>心形</title>
<body>
    <div class="heart"></div>
</body>
<style>
    body {
        width: 100%;
        height: 100vh;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }
    .heart {
        width: 200px;
        height: 200px;
        background: red;
        position: relative;
        transform: rotate(45deg);
    }
    .heart::before {
        content: '';
        width: 200px;
        height: 100px;
        background: red;
        position: absolute;
        left: 0;
        top: -100px;
        border-radius: 100px 100px 0 0;
    }
    .heart::after {
        content: '';
        width: 100px;
        height: 200px;
        background: red;
        position: absolute;
        left: -100px;
        top: 0;
        border-radius: 100px 0 0 100px;
    }

</style>
</html>

而且通过这次实验,我们得出一个重要的结论:

伪元素::before::after会随着主元素旋转而旋转。

让心跳动起来

那么如何让心脏跳动起来呢?

需要用到transform属性,transform可以使用多个变形函数,如:

transform: rotate(45deg) scale(1);

来看一下我们的最终效果:

e65a5a46-e944-4c42-881a-33ba7f79082e.gif

心脏跳动的几个关键要素:

  1. 使用默认的ease动画速度:即animation-timing-function: ease;
  2. 轮流反向播放动画:即animation-direction: alternate;,否则心脏只能从小变大,而从大变小变成了瞬时,不美观。
  3. 动画状态使用transform: rotate(45deg) scale(xxx)

详细代码如下:

<!DOCTYPE html>
<title>心形</title>
<body>
    <div class="heart"></div>
</body>
<style>
    body {
        width: 100%;
        height: 100vh;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }
    .heart {
        width: 200px;
        height: 200px;
        background: red;
        position: relative;
        transform: rotate(45deg) scale(0.5);
        animation: heartbit 0.5s alternate infinite;
    }
    .heart::before {
        content: '';
        width: 200px;
        height: 100px;
        background: red;
        position: absolute;
        left: 0;
        top: -100px;
        border-radius: 100px 100px 0 0;
    }
    .heart::after {
        content: '';
        width: 100px;
        height: 200px;
        background: red;
        position: absolute;
        left: -100px;
        top: 0;
        border-radius: 100px 0 0 100px;
    }
    @keyframes heartbit {
        0% {
            transform: rotate(45deg) scale(0.5);
        }
        100% {
            transform: rotate(45deg) scale(1);
        }
    }
</style>
</html>

最后

说点别的,日更文23天了,基本已经锁定了双肩包,这时候就面临一个问题,第22篇→第28篇的7篇文章与第1篇→第7篇的7篇文章完全不同,一个写7篇只能拿个杯子,一个写7篇就能那个颈椎按摩器,妙啊!