效果展示
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: 6px solid white;
position: absolute;
left: 0;
top: 0;
animation: rotation 4s ease-in-out infinite;
}
span::after {
border-color: red;
animation-delay: 2s;
}
@keyframes rotation {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(360deg)
}
}
原理详解
步骤1
使用span标签,设置
- 宽度、高度均为96px
- 相对定位
width: 96px;
height: 96px;
position: relative;
步骤2
利用span::before和span::after充当白色、红色方框
设置为
- 绝对定位 (left: 0; top: 0;)
- 宽度、高度均为96px
- 边框:6px solid white;
span::before, span::after {
width: 96px;
height: 96px;
border: 6px solid white;
position: absolute;
left: 0;
top: 0;
}
效果图如下
步骤3
修改span::after背景色为红色
span::after {
border-color: red;
}
效果图如下
注:span::before和after位置发生了重叠,图中其实红色与白色方块位于同一位置,只是after后面设置,最后显示为红色了
步骤4
为span::after、span::before添加动画
- 顺时针旋转 4s 无限循环
- 速度曲线:ease-in-out
animation: rotation 4s ease-in-out infinite;
@keyframes rotation {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(360deg)
}
}
效果图如下
步骤5
步骤4动画效果是为span::before和span::after同时添加的
我们需要将二者显示效果分开
对span::after动画开始时间进行延时,分离span::before和span::after
span::after {
animation-delay: 2s;
}
效果图如下