「HTML+CSS」自定義加載動(dòng)畫(huà)【012】
效果展示

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;
border: 10px solid white;
border-radius: 50%;
display: flex;
justify-content: center;
position: relative;
animation: rotation 2s linear infinite;
}
span::before{
position: absolute;
top: -21px;
content: '';
width: 32px;
height: 32px;
background: red;
border-radius: 50%;
}
@keyframes rotation {
0% { transform: rotate(0deg) }
100% { transform: rotate(360deg)
}
}
原理詳解
步驟1
設(shè)置span元素
寬度/高度均為:96px 邊框?yàn)椋喊咨?10px solid
width : 96px;
height: 96px;
border: 10px solid white;
效果圖如下

步驟2
使用span::before偽類(lèi),作為紅色小球部分
設(shè)置span::before
寬度、高度均為:32px 背景色:紅色 絕對(duì)定位
position: absolute;
width: 32px;
height: 32px;
background: red;
效果圖如下

步驟3
將span::before移動(dòng)至水平中間
這是海轟的方法是使用flex布局(對(duì)span設(shè)置)
display: flex;
justify-content: center; /*水平正中*/
效果圖如下

步驟4
將紅色方塊中心移動(dòng)至白色邊框中軸(重點(diǎn)?。?/p>
top: -21px;
效果圖如下
上述效果圖解

步驟5
對(duì)兩個(gè)元素進(jìn)行圓角化
border-radius: 50%;
效果圖如下

步驟6
添加旋轉(zhuǎn)動(dòng)畫(huà)
animation: rotation 2s linear infinite;
// 動(dòng)畫(huà)實(shí)現(xiàn)
@keyframes rotation {
0% { transform: rotate(0deg) }
100% { transform: rotate(360deg)
}
}
效果圖如下

疑點(diǎn)解釋
疑問(wèn)1
為什么需要將紅色方塊中心和上邊框中心重合???
答:兩個(gè)中心重合,從視覺(jué)上可以感覺(jué)到二者是粘附在一起的,完全重合就可以體現(xiàn)這一點(diǎn)。如果不是完全重合,就會(huì)感覺(jué)小球有點(diǎn)搖搖欲墜的感覺(jué),參考下圖:

疑問(wèn)2
top=-21px是如何計(jì)算出來(lái)的?
首先理解移動(dòng)的初始、終點(diǎn)位置關(guān)系

通過(guò)前面的設(shè)置我們可以知道
邊框的總高度為10px,那么中心的高度就是10/2=5px 紅色部分的寬度/高度均為32px,那么中心高度就是32/2=16px
所以,下面中心欲與上面中心重合
那么下面的中心就需要向上移動(dòng)(5+16px)
故top=-21px
結(jié)語(yǔ)
學(xué)習(xí)來(lái)源:
https://codepen.io/bhadupranjal/pen/vYLZYqQ
文章僅作為學(xué)習(xí)筆記,記錄從0到1的一個(gè)過(guò)程。
希望對(duì)您有所幫助,如有錯(cuò)誤歡迎小伙伴指正~
我是 海轟?(?ˊ?ˋ)?
如果您覺(jué)得寫(xiě)得可以的話請(qǐng)點(diǎn)個(gè)贊吧
謝謝支持??

評(píng)論
圖片
表情
