CSS3实现心跳的样子
先上效果图:
html部分:
<div class="box"></div>
思路:先画一个爱心,用两个圆和一个旋转45度的正方形,就像下图:
这里为了好区分所以使用了红绿蓝三种颜色,透明的设置成了0.6,实际上直接把颜色都设置成红色就可以了。
这里因为我只用了一个div标签,所以两个圆就用伪类元素:before
和:after
来做的。
transform
变形;
translate
平移:translate(x, y)
;
rotate
旋转:rotate(deg)
,正值为顺时针,负值为逆时针,deg为旋转度数;
/* 正方形 */
.box {
width: 100px;
height: 100px;
background-color: #f66;
transform: rotate(-45deg); /* 旋转45度 */
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
/* 两个圆 */
.box::before, .box::after {
content: '';
width: 100px;
height: 100px;
display: block;
background-color: #f66;
border-radius: 50%;
}
.box::before {
transform: translate(0, -50%); /* 第一个圆平移到左上角 */
}
.box::after {
transform: translate(50%, -100%); /* 第二个圆平移右上角 */
}
接下来就是加上动画,这里使用@keyframes规则创建动画,内容如下:
@keyframes animationname {keyframes-selector {css-styles;}}
@keyframes beat {
0% {
width: 100px;
height: 100px;
}
15% {
width: 120px;
height: 120px;
}
30% {
width: 100px;
height: 100px;
}
45% {
width: 120px;
height: 120px;
}
60% {
width: 100px;
height: 100px;
}
100% {
width: 100px;
height: 100px;
}
}
最后就是把动画属性animation
加到我们的div和伪类元素上
animation
动画:animation: name duration timing-function delay iteration-count direction
【1】name
:规定需要绑定到选择器的 keyframe 名称
【2】duration
:规定完成动画所花费的时间,以秒或毫秒计
【3】timing-function
规定动画的速度曲线
【4】delay
:规定在动画开始之前的延迟
【5】iteration-count
规定动画应该播放的次数
【6】direction
:规定是否应该轮流反向播放动画
.box {
......
animation: beat 1.5s infinite;
}
.box::before, .box::after {
......
animation: beat 1.5s infinite;
}
这样,爱心就能动起来咯。
最后附上全代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>心跳的样子 *^_^* </title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #f66;
transform: rotate(-45deg);
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
animation: beat 1.5s infinite;
}
.box::before, .box::after {
content: '';
width: 100px;
height: 100px;
display: block;
background-color: #f66;
border-radius: 50%;
animation: beat 1.5s infinite;
}
.box::before {
transform: translate(0, -50%);
}
.box::after {
transform: translate(50%, -100%);
}
@keyframes beat {
0% {
width: 100px;
height: 100px;
}
15% {
width: 120px;
height: 120px;
}
30% {
width: 100px;
height: 100px;
}
45% {
width: 120px;
height: 120px;
}
60% {
width: 100px;
height: 100px;
}
100% {
width: 100px;
height: 100px;
}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
完结