纯样式实现星空动态背景

定义五个层次

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>星空背景</title>
    <link rel="stylesheet" href="./style/index2.css">
</head>
<body>
    <div class="layer1"></div>
    <div class="layer2"></div>
    <div class="layer3"></div>
    <div class="layer4"></div>
    <div class="layer5"></div>
</body>
</html>
body{
    background-color: #080C10;
}
@function star($n) {
    $res: '#{random(100)}vw #{random(100)}vh 0 #fff'; 
    @for $i from 2 through $n {
        $res: $res + ', #{random(100)}vw #{random(100)}vh 0 #fff'; 
    }
    @return unquote($res);
}

@keyframes moveUp {
    to {
        transform: translateY(-100vh);
    }
}

$n:5;
$duration: 400s;
$count:1000;
@for $i from 1 through $n {
    $duration: floor($duration/2); //每个层次的移动速度不一致
    $count: floor($count/2); //每个层次的星星个数不一致(近处星星少,远处的星星多)
    .layer#{$i}{
        position: fixed;
        width: #{$i}px;            //实现近大远小
        height: #{$i}px;
        left: 0;
        top: 0;
        background-color: #fff;
        border-radius: 50%;
        // 通过盒子阴影来增加星星个数,避免渲染多个DOM 
        // box-shadow: 10vw 10vh 0 #fff, 20vw 30vh 0 #fff; 
        box-shadow: star($count);
        animation: moveUp 10s linear infinite; // 星星往上移动动画
    }
    
    // 增加伪类填充layer1往上但下方空白
    .layer#{$i}::after{
        content: '';
        position: inherit;
        width: inherit;
        height: inherit;
        left: inherit;
        top: 100vh;
        border-radius: inherit;
        box-shadow: inherit;
    }
}

QQ20251020-111149

posted @ 2025-10-20 11:13  原语  阅读(10)  评论(0)    收藏  举报