【动画消消乐】 平时学习生活比较枯燥,无意之间对一些网页、应用程序的过渡/加载动画产生了浓厚的兴趣,想知道具体是如何实现的? 便在空闲的时候学习下如何使用css实现一些简单的动画效果,文章仅供作为自己的学习笔记,记录学习生活,争取理解动画的原理,多多“消灭”动画!
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<section><span></span></section>
</body>
</html>
CSS
html, body {
margin: 0;
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
background: #263238;
}
section {
width: 650px;
height: 300px;
padding: 10px;
position: relative;
display: flex;
align-items: center;
justify-content: center;
/* 红色边框仅作提示 */
border: 2px solid red;
}
span {
width: 96px;
height: 96px;
display: inline-block;
position: relative;
border: 2px solid white;
animation: rotation 4s linear infinite;
}
span::before, span::after {
content: '';
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
border: 2px solid red;
width: 76px;
height: 76px;
animation: rotationBack 3s linear infinite;
transform-origin: center center;
}
span::after {
width: 56px;
height: 56px;
border-color: white;
animation: rotation 2s linear infinite;
}
@keyframes rotationBack {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(-360deg)
}
}
@keyframes rotation {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(360deg)
}
}
使用span标签,设置
width: 96px;
height: 96px;
position: relative;
border: 2px solid white;
效果图如下
利用span::before和span::after伪元素充当span里面的白色/红色小方框
同时设置
span::before, span::after {
content: '';
position: absolute;
/*使得元素居于正中间*/
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
border: 2px solid red;
width: 76px;
height: 76px;
}
效果图如下
再分离span::after
设置为
/*代码放在before/after的后面 这样才会对after进行重新设置*/
span::after {
width: 56px;
height: 56px;
border-color: white;
}
效果图如下
为span添加动画
animation: rotation 4s linear infinite;
@keyframes rotation {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(360deg)
}
}
同时对span::after也使用该动画,修改下动画持续时间为2s
animation: rotation 2s linear infinite;
效果图如下
步骤4中span::before尽管没有设置动画,但是其也是位于span上,所以也随span一起旋转
这里我们对span::before添加一个动画,旋转方向相反即可
animation: rotationBack 3s linear infinite;
@keyframes rotationBack {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(-360deg)
}
}
最终效果图如下
学习参考: