css雪花制作教程
使用纯CSS制作雪花效果
通过CSS的@keyframes和伪元素可以创建动态雪花效果。以下是一个基础实现方案:
<!DOCTYPE html>
<html>
<head>
<style>
.snowflake {
position: absolute;
color: white;
font-size: 1em;
animation: fall linear infinite;
}
@keyframes fall {
to {
transform: translateY(100vh);
}
}
</style>
</head>
<body>
<div class="snowflake">❄</div>
</body>
</html>
添加随机化效果
通过CSS变量和JavaScript增强随机性:
.snowflake {
--x-pos: 0;
--fall-duration: 10s;
--delay: 0s;
left: calc(var(--x-pos) * 1vw);
animation: fall var(--fall-duration) var(--delay) linear infinite;
}
@keyframes fall {
0% {
transform: translateY(-10vh) rotate(0deg);
}
100% {
transform: translateY(110vh) rotate(360deg);
}
}
function createSnowflakes() {
const count = 50;
for (let i = 0; i < count; i++) {
const flake = document.createElement('div');
flake.className = 'snowflake';
flake.innerHTML = '❄';
flake.style.setProperty('--x-pos', Math.random());
flake.style.setProperty('--fall-duration', 5 + Math.random() * 10 + 's');
flake.style.setProperty('--delay', Math.random() * 5 + 's');
flake.style.fontSize = Math.random() * 10 + 5 + 'px';
document.body.appendChild(flake);
}
}
优化性能的版本
使用will-change和transform提升渲染性能:
.snowflake {
will-change: transform;
pointer-events: none;
position: fixed;
top: -10%;
z-index: 9999;
}
多种雪花形状
通过伪元素创建不同形状:
.snowflake::before {
content: '❄';
}
.snowflake:nth-child(2n)::before {
content: '✦';
}
.snowflake:nth-child(3n)::before {
content: '❉';
}
响应式调整
根据窗口大小调整雪花数量:
window.addEventListener('resize', () => {
const flakes = document.querySelectorAll('.snowflake');
const targetCount = Math.floor(window.innerWidth / 20);
if (flakes.length < targetCount) {
createSnowflakes(targetCount - flakes.length);
}
});






