Appearance
星空闪烁
纯 CSS 实现的深空星空效果,多层次大小不同的星星配合闪烁动画,营造出梦幻的宇宙氛围。
实时预览
代码
css
.stars-container {
width: 100%;
height: 300px;
background: radial-gradient(ellipse at center, #0f172a 0%, #0a0a1a 50%, #000 100%);
position: relative;
overflow: hidden;
}
.star {
position: absolute;
border-radius: 50%;
background: #fff;
}
.star.s1 { width: 1px; height: 1px; animation: twinkle 3s ease-in-out infinite; }
.star.s2 { width: 2px; height: 2px; animation: twinkle 4s ease-in-out infinite; }
.star.s3 { width: 3px; height: 3px; animation: twinkle 2.5s ease-in-out infinite; }
@keyframes twinkle {
0%, 100% { opacity: 0.3; transform: scale(1); }
50% { opacity: 1; transform: scale(1.5); }
}html
<div class="stars-container">
<div class="star s1"></div>
<div class="star s2"></div>
<!-- 20+ stars with varied positions -->
</div>纯 CSS 实现的星空闪烁背景动画——通过渐变、滤镜和 @keyframes 创建动态背景效果。无需 Canvas、WebGL 或任何 JavaScript,即可让页面背景"活"起来。
快速使用
- 复制 CSS 代码(含
@keyframes)到你的样式文件中 - 将背景动画样式应用到目标容器元素上
- 调整
background-size和animation-duration控制效果 - 确保容器有明确的高度(
min-height),否则背景可能不可见
使用场景
- 品牌落地页:用渐变流动或极光背景提升页面的高级感
- 技术/黑客主题页面:矩阵代码雨或粒子背景传递科技氛围
- 创意/设计类网站:浮动光斑或网格动画展现设计感
- 节日/活动页面:动态背景配合主题色营造节日氛围
常见问题
Q: 背景动画会消耗很多 CPU 吗? A: 会消耗一定的 GPU 资源。建议在用户不可见时(如切换标签页)暂停动画,用 animation-play-state: paused 配合 document.hidden API。移动端慎用多个滤镜叠加。
Q: 如何让背景动画不影响内容可读性? A: 在动画层之上加一个半透明遮罩层(如 background: rgba(0,0,0,0.4)),或将文字放在独立的叠层中。也可以降低动画的 opacity 到 0.3~0.5。
Q: 背景动画在所有浏览器下都正常吗? A: conic-gradient 需要较新浏览器版本。@property 仅 Chrome/Edge。建议提供降级方案:用 linear-gradient + background-position 动画替代。
浏览器兼容性
| 浏览器 | 兼容性 |
|---|---|
| Chrome / Edge | ✅ 完全支持(含 conic-gradient、@property) |
| Firefox | ✅ 基本支持(不含 @property) |
| Safari | ✅ 基本支持 |
| 移动端浏览器 | ✅ 完全支持 |
| IE 11 | ❌ 高级渐变和动画不支持 |
使用说明
| 属性 | 说明 |
|---|---|
radial-gradient | 从中心到边缘的渐变,模拟深空 |
width/height | 星星大小:1px/2px/3px 三种等级 |
animation-duration | 闪烁周期,2-5s 之间变化增加真实感 |
animation-delay | 错开闪烁,避免同步明灭 |
box-shadow | 为亮星添加光晕效果 |
background | 径向渐变背景营造宇宙纵深感 |
提示: 将一些星星的 background 设为 #ffe4b5(暖色)或 #b0d0ff(冷色),可以让星空更丰富。亮星用 box-shadow 添加光晕效果。