效果展示
Demo代码
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;
}
span::before,
span::after{
content: '';
width : 96px;
height: 96px;
border:3px solid white;
position: absolute;
left:0;
top: 0;
animation: rotationBreak 4s ease-in-out infinite alternate;
}
span::after{
border-color: red;
animation-direction: alternate-reverse;
}
@keyframes rotationBreak {
0% { transform: rotate(0) }
25% { transform: rotate(90deg)}
50% { transform: rotate(180deg) }
75% { transform: rotate(270deg)}
100% { transform: rotate(360deg) }
}
原理详解
步骤1
使用span标签,设置
- 宽度、高度均为96px
- 相对定位
width: 96px;
height: 96px;
position: relative;
步骤2
利用span::before和span::after,充当白色、红色方框
同时设置
- 绝对定位( left: 0 top: 0)
- 宽度、高度均为96px
- 边框:3px solid white
content: '';
width: 96px;
height: 96px;
border: 3px solid white;
position: absolute;
left: 0;
top: 0;
效果图如下
步骤3
为区分before和after
设置span::after背景色为红色
span::after {
border-color: red;
}
效果图如下
注:span::before和after位置发生了重叠,图中其实红色与白色方块位于同一位置,只是after后面设置,最后显示为红色了
步骤4
为span::before和span::after添加动画
- 顺时针旋转(0-360度) 4s 无限循环
- 速度曲线:ease-in-out
- 动画轮流反向播放 alternate
animation: rotation 4s ease-in-out infinite alternate;
@keyframes loading {
0% {
transform: rotate(0)
}
25% {
transform: rotate(90deg)
}
50% {
transform: rotate(180deg)
}
75% {
transform: rotate(270deg)
}
100% {
transform: rotate(360deg)
}
}
效果图如下
步骤5
步骤4所设置的动画是为before和after同时设置的,二者的变化过程完全一致
为了视觉上分离before和after
我们对after动画进行反向处理(这样before和after就可以分开显示了)
span::after {
animation-direction: alternate-reverse;
}
效果图如下