效果展示
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: 8px solid white;
position: absolute;
left: 0;
top: 0;
animation: loading 4s ease-in-out infinite;
}
span::after {
border-color: red;
animation-delay: 2s;
}
@keyframes loading {
0% {
transform: scale(0);
opacity: 1;
}
100% {
transform: scale(1);
opacity: 0;
}
}
原理详解
步骤1
使用span标签,设置
- 宽度、高度均为96px
- 相对定位
width: 96px;
height: 96px;
position: relative;
步骤2
利用span::before和span::after,充当白色、红色方框
同时设置
- 绝对定位( left: 0 top: 0)
- 宽度、高度均为96px
- 边框:8px solid white
content: '';
width: 96px;
height: 96px;
border: 8px 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%)大小为0(相对于原大小),最后变为1(相对于原大小)
- 颜色:初始(0%)颜色透明级别为1,最后变为0
animation: loading 4s ease-in-out infinite;
@keyframes loading {
0% {
transform: scale(0);
opacity: 1;
}
100% {
transform: scale(1);
opacity: 0;
}
}
效果图如下
步骤5
步骤4所设置的动画是为before和after同时设置的,二者的变化过程完全一致
为了视觉上分离before和after
我们对after动画开始时间延迟(这样before和after就可以分开显示了)
span::after {
animation-delay: 2s;
}
效果图如下