效果展示
在这里插入图片描述
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;
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)
}
}
原理详解
步骤1
使用span标签,设置
- 宽度、高度均为96px
- 边框:2px solid white
- 相对定位
width: 96px;
height: 96px;
position: relative;
border: 2px solid white;
效果图如下
在这里插入图片描述
步骤2
利用span::before和span::after伪元素充当span里面的白色/红色小方框
同时设置
- 宽度、高度为76px
- 绝对定位( left: 0; right: 0; top: 0; bottom: 0; margin: auto;)
- 边框:2px solid red
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;
}
效果图如下
在这里插入图片描述
步骤3
再分离span::after
设置为
- 宽度、高度均为56px
- 边框颜色:白色
/*代码放在before/after的后面 这样才会对after进行重新设置*/
span::after {
width: 56px;
height: 56px;
border-color: white;
}
效果图如下
在这里插入图片描述
步骤4
为span添加动画
- 顺时针旋转(0-360度) 无限循环
- 速度曲线:linear
animation: rotation 4s linear infinite;
@keyframes rotation {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(360deg)
}
}
同时对span::after也使用该动画,修改下动画持续时间为2s
animation: rotation 2s linear infinite;
效果图如下
在这里插入图片描述
步骤5
步骤4中span::before尽管没有设置动画,但是其也是位于span上,所以也随span一起旋转
这里我们对span::before添加一个动画,旋转方向相反即可
animation: rotationBack 3s linear infinite;
@keyframes rotationBack {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(-360deg)
}
}
最终效果图如下
在这里插入图片描述
结语
学习参考:
文章仅作为学习笔记,记录从0到1的一个过程
希望对您有所帮助,如有错误欢迎小伙伴指正~
我是海轰ଘ(੭ˊᵕˋ)੭,如果您觉得写得可以的话,请点个赞吧
谢谢支持❤️