想让你的网站动起来吗?试试纯css打造的跳动爱心动画!无需javascript,无需库,只需css代码就能实现。
步骤一:创建爱心形状
首先,我们用CSS的::before和::after伪元素创建一个爱心:
<code class="html"><div class="heart"></div></code>
<code class="css">.heart {
position: relative;
width: 100px;
height: 100px;
background-color: red;
transform: rotate(-45deg);
margin: 50px auto;
}
.heart::before,
.heart::after {
content: "";
position: absolute;
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%;
}
.heart::before {
top: -50px;
left: 0;
}
.heart::after {
left: 50px;
top: 0;
}</code>大功告成!一个爱心形状出现了!接下来,让它跳动起来!
步骤二:添加跳动动画
立即学习“前端免费学习笔记(深入)”;
我们使用@keyframes规则来实现爱心的缩放动画:
<code class="css">@keyframes heartbeat {
0%, 100% { transform: scale(1) rotate(-45deg); }
50% { transform: scale(1.2) rotate(-45deg); }
}
.heart {
animation: heartbeat 1s infinite;
}</code>现在爱心开始有节奏地跳动了!
步骤三:微调动画效果
为了使动画更自然,我们调整一下动画的节奏:
<code class="css">@keyframes heartbeat {
0%, 100% { transform: scale(1) rotate(-45deg); }
30% { transform: scale(1.2) rotate(-45deg); }
60% { transform: scale(1) rotate(-45deg); }
80% { transform: scale(1.1) rotate(-45deg); }
}
.heart {
animation: heartbeat 1.2s infinite ease-in-out;
}</code>现在动画更加流畅,更像真实的心跳了。
完整代码:
<code class="html"><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Heartbeat Animation</title>
<style>
.heart {
position: relative;
width: 100px;
height: 100px;
background-color: red;
transform: rotate(-45deg);
margin: 50px auto;
animation: heartbeat 1.2s infinite ease-in-out;
}
.heart::before,
.heart::after {
content: "";
position: absolute;
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%;
}
.heart::before {
top: -50px;
left: 0;
}
.heart::after {
left: 50px;
top: 0;
}
@keyframes heartbeat {
0%, 100% { transform: scale(1) rotate(-45deg); }
30% { transform: scale(1.2) rotate(-45deg); }
60% { transform: scale(1) rotate(-45deg); }
80% { transform: scale(1.1) rotate(-45deg); }
}
</style>
</head>
<body>
<div class="heart"></div>
</body>
</html></code>动画效果展示:

总结:
CSS的强大之处在于,即使是简单的动画,也能轻松实现,无需依赖JavaScript。你可以根据自己的喜好调整颜色、大小和动画速度,创造出独一无二的爱心动画,应用于你的网站加载页面、情人节主题页面等。 快来试试吧! ❤️
以上就是如何使用CSS创建心跳动画的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号