效果图
盒子的阴影可以设置多个,所以我们可以通过阴影实现星光的效果,但纯写 css 过于抽象,我们可以利用 sass 的循环语法、函数与变量编写
HTML结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./index.css"> </head> <body> <div class="layer1"></div> <div class="layer2"></div> <div class="layer3"></div> <div class="title">Sass 星空</div> </body> </html>
|
SASS代码
提示:
-
对SASS的编译不要用 VScode 的插件:easy sass,可能会出现函数识别导致编译失败的问题
-
可以在 node 环境下,安装 sass:npm i sass
-
后执行 npx sass [sass文件路径] [编译转换后的css输出文件路径] --no-source-map -w
npx sass index.scss index.css --no-source-map -w
-
npx:暂时把 sass 加入环境变量中,仅在此命令行操作有效
-
sass:安装 sass 自带的执行命令
-
–no-source-map:取消源映射,source-map里面存放着sass与css的映射信息,通过此命令可以取消该文件的生成
-
-w:监听sass/scss的文件内容变化,自动更新生成的css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| // 背景底色 html { height: 100%;
background: radial-gradient(ellipse at bottom, #1b2735 0%, #090a0f 100%); overflow: hidden; } .title { position: absolute; top: 50%; left: 0; right: 0; color: #fff; text-align: center; font-family: "lato", sans-serif; font-weight: 300; font-size: 50px; letter-spacing: 10px; margin-top: -60px; padding-left: 10px; // 渐变背景,将文本背景设置为透明,并设置背景颜色为 #38495a // 即将文字展示为背景颜色 background: linear-gradient(white, #38495a); -webkit-background-clip: text; background-clip: text; color: transparent; }
// 创建星光(阴影)函数 @function createShadow($n) { // 定义阴影变量 $shadow: "#{random($limit: 100)}vw #{random($limit: 100)}vh #fff"; @for $i from 2 through $n { // 每次循环向 $shadow 中添加新的阴影 $shadow: "#{$shadow}, #{random($limit: 100)}vw #{random($limit: 100)}vh #fff"; } // unquote() 函数用于将字符串转换为 CSS 属性值,即去掉字符串 @return unquote($shadow); }
// 定义星光(阴影)初始数量 $count: 1000; // 定义动画初始时间 $duration: 400s; @for $i from 1 through 3 { // 每次循环时将数量和动画时间减半,以达到不同层级的动画效果 $count: floor(calc($count / 2)); $duration: floor(calc($duration / 2));
// 输出调试信息 @debug "count #{$count}"; @debug "duration #{$duration}"; // 创建层级的样式 .layer#{$i} { $size: #{$i}px; position: fixed; width: $size; height: $size; border-radius: 50%; left: 0; right: 0; background: #f40; box-shadow: createShadow($count); animation: moveUp $duration linear infinite; // 为了动画的流畅和无缝衔接,在 &::after 中设置相同的参数 &::after { content: ""; position: fixed; top: 100vh; left: 0; width: inherit; height: inherit; box-shadow: inherit; background: inherit; border-radius: inherit; } } }
// 移动动画 @keyframes moveUp { 100% { transform: translateY(-100vh); } }
|