总体思路
- 利用
box-shadow多个属性值来设置多个阴影偏移效果
position: fixed;
height: 1px;
width: 1px;
border-radius: 50%;
box-shadow: 9vw 88vh #fff, 48vw 88vh #fff, 53vw 46vh #fff, 46vw 78vh #fff.....
- 利用
random(n)来随机生成数值 - SASS for循环
@for $i from $j through $n{}重复拼接box-shadow的值 - 给图层添加动画效果
@keyframes xxx{} - 为避免动画过程中效果缺失,复制一个图层
::after,所有属性继承自父属性,但需要向下偏移一个屏幕位置。
content: '';
position: fixed;
width: inherit;
height: inherit;
border-radius: inherit;
left: 0;
top: 100vh;
box-shadow: inherit;
- 最后循环生成多个图层
项目初始化
准备index.html、index.scss
npm init
npm i sass -D
package.json中在scripts配置"dev": "sass index.scss index.css -w --no-source-map" 使用sass命令将根目录下index.scss 解析为/到根目录下 index.scc,-w 监听, --no-source-map 不生成源码地图。
npm run dev
在html中需引入的是 index.scc
源码
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="index.css">
<title>SASS星空</title>
</head>
<body>
<div class="layout1"></div>
<div class="layout2"></div>
<div class="layout3"></div>
<div class="layout4"></div>
<div class="title">SASS星空</div>
</body>
</html>
SCSS
@mixin absolute{
position: absolute;
top: 50%;
left: 0;
right: 0;
}
html{
height: 100%;
background: radial-gradient(ellipse at bottom, #1b2735 0%, #090a0f 100%);
overflow: hidden;
}
.title{
@include absolute;
font-size: 50px;
color: #fff;
text-align: center;
font-weight: 300;
letter-spacing: 10px;
margin-top: -60px;
padding-left: 10px;
background: linear-gradient(white,#38495a);
background-clip: text;
-webkit-background-clip: text;
color: transparent;
}
// 生成多个box-shadow 属性值
@function getShadows($n){
$shadow: "#{random(100)}vw #{random(100)}vh #fff";
@for $i from 2 through $n{
$shadow: "#{$shadow}, #{random(100)}vw #{random(100)}vh #fff";
}
@return unquote($shadow); // 去除双引号
}
$duration:1000s; // 动画时间
$count: 1000; // 星星总数
@for $i from 1 through 4{
$duration: floor($duration/2); // 动画时间依次减半
$count: floor($count/2); // 星星总数依次减半
.layout#{$i}{
$size: #{$i}px; // 每层星星大小 1 2 3 4px
position: fixed;
height: $size;
width: $size;
border-radius: 50%;
box-shadow: getShadows($count);
animation: moveup $duration linear infinite;
&::after{
content: '';
position: fixed;
width: inherit;
height: inherit;
border-radius: inherit;
left: 0;
top: 100vh;
box-shadow: inherit;
}
}
}
@keyframes moveup{
to{
transform: translateY(-100vh);
}
}