「HTML+CSS」自定义加载动画【012】

海轰Pro

共 3330字,需浏览 7分钟

 · 2021-04-27

效果展示

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{
  margin0;
  height100%;
}
body{
  display: flex;
  justify-content: center;
  align-items: center;
  background#263238;
}
section {
    width650px;
    height300px;
    padding10px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    /* 红色边框仅作提示 */
    border2px solid red;
}

span{
  width 96px;
  height96px;
  border10px solid white;
  border-radius50%
    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-radius50%;
}

@keyframes rotation {
  0% { transformrotate(0deg) }
  100% { transformrotate(360deg)
  }
}

原理详解

步骤1

设置span元素

  • 宽度/高度均为:96px
  • 边框为:白色 10px solid
width : 96px;
height: 96px;
border: 10px solid white;

效果图如下

步骤2

使用span::before伪类,作为红色小球部分

设置span::before

  • 宽度、高度均为:32px
  • 背景色:红色
  • 绝对定位
position: absolute;
width:  32px;
height:  32px;
background: red;

效果图如下

步骤3

将span::before移动至水平中间

这是海轰的方法是使用flex布局(对span设置)

display: flex;
justify-content: center; /*水平正中*/

效果图如下

步骤4

将红色方块中心移动至白色边框中轴(重点!)

 top: -21px;

效果图如下

上述效果图解

步骤5

对两个元素进行圆角化

border-radius: 50%;

效果图如下

步骤6

添加旋转动画

animation: rotation 2s linear infinite;
// 动画实现
@keyframes rotation {
  0% { transform: rotate(0deg) }
  100% { transform: rotate(360deg)
  }
}

效果图如下

疑点解释

疑问1

为什么需要将红色方块中心和上边框中心重合啊?

答:两个中心重合,从视觉上可以感觉到二者是粘附在一起的,完全重合就可以体现这一点。如果不是完全重合,就会感觉小球有点摇摇欲坠的感觉,参考下图:

疑问2

top=-21px是如何计算出来的?

首先理解移动的初始、终点位置关系

通过前面的设置我们可以知道

  1. 边框的总高度为10px,那么中心的高度就是10/2=5px
  2. 红色部分的宽度/高度均为32px,那么中心高度就是32/2=16px

所以,下面中心欲与上面中心重合

那么下面的中心就需要向上移动(5+16px)

故top=-21px

结语

学习来源:

https://codepen.io/bhadupranjal/pen/vYLZYqQ

文章仅作为学习笔记,记录从0到1的一个过程。

希望对您有所帮助,如有错误欢迎小伙伴指正~

我是 海轰ଘ(੭ˊᵕˋ)੭

如果您觉得写得可以的话请点个赞吧

谢谢支持❤️


浏览 5
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报