效果展示
在這里插入圖片描述
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標(biāo)簽仰楚,設(shè)置
- 寬度、高度均為96px
- 相對(duì)定位
width: 96px;
height: 96px;
position: relative;
步驟2
利用span::before和span::after充當(dāng)白色举哟、紅色方框
設(shè)置為
- 絕對(duì)定位 (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位置發(fā)生了重疊迅矛,圖中其實(shí)紅色與白色方塊位于同一位置妨猩,只是after后面設(shè)置,最后顯示為紅色了
步驟4
為span::after秽褒、span::before添加動(dòng)畫
- 順時(shí)針旋轉(zhuǎn) 4s 無限循環(huán)
- 速度曲線:ease-in-out
animation: rotation 4s ease-in-out infinite;
@keyframes rotation {
0% {
transform: rotate(0deg)
}
100% {
transform: rotate(360deg)
}
}
效果圖如下
在這里插入圖片描述
步驟5
步驟4動(dòng)畫效果是為span::before和span::after同時(shí)添加的
我們需要將二者顯示效果分開
對(duì)span::after動(dòng)畫開始時(shí)間進(jìn)行延時(shí)壶硅,分離span::before和span::after
span::after {
animation-delay: 2s;
}
效果圖如下
在這里插入圖片描述