css 制作下雨特效
使用 CSS 制作下雨特效
通过 CSS 动画和伪元素可以模拟下雨效果。以下是实现方法:
创建雨滴元素
定义雨滴的基本样式,使用伪元素 ::before 或 ::after 生成雨滴形状:
.raindrop {
position: absolute;
width: 2px;
height: 15px;
background: linear-gradient(to bottom, transparent, #a0d8f3);
border-radius: 0 0 5px 5px;
}
添加下落动画
使用 @keyframes 定义雨滴从顶部到底部的动画:
@keyframes fall {
from { transform: translateY(-100px) rotate(15deg); }
to { transform: translateY(100vh) rotate(15deg); }
}
随机化雨滴位置和延迟
通过 JavaScript 动态生成雨滴并设置随机属性:
const container = document.querySelector('.rain-container');
for (let i = 0; i < 50; i++) {
const drop = document.createElement('div');
drop.className = 'raindrop';
drop.style.left = `${Math.random() * 100}vw`;
drop.style.animation = `fall ${0.5 + Math.random() * 1}s linear infinite`;
drop.style.animationDelay = `${Math.random() * 2}s`;
container.appendChild(drop);
}
添加涟漪效果(可选)
当雨滴"落地"时创建涟漪动画:

@keyframes ripple {
0% { transform: scale(0); opacity: 1; }
100% { transform: scale(3); opacity: 0; }
}
.ripple {
position: absolute;
width: 10px;
height: 10px;
border-radius: 50%;
background: rgba(160, 216, 243, 0.5);
animation: ripple 0.5s linear forwards;
}
完整示例代码
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
height: 100vh;
overflow: hidden;
background: #222;
}
.rain-container {
position: relative;
width: 100%;
height: 100%;
}
.raindrop {
position: absolute;
width: 2px;
height: 15px;
background: linear-gradient(to bottom, transparent, #a0d8f3);
border-radius: 0 0 5px 5px;
}
@keyframes fall {
from { transform: translateY(-100px) rotate(15deg); }
to { transform: translateY(100vh) rotate(15deg); }
}
@keyframes ripple {
0% { transform: scale(0); opacity: 1; }
100% { transform: scale(3); opacity: 0; }
}
.ripple {
position: absolute;
width: 10px;
height: 10px;
border-radius: 50%;
background: rgba(160, 216, 243, 0.5);
animation: ripple 0.5s linear forwards;
}
</style>
</head>
<body>
<div class="rain-container"></div>
<script>
const container = document.querySelector('.rain-container');
// 创建雨滴
for (let i = 0; i < 80; i++) {
const drop = document.createElement('div');
drop.className = 'raindrop';
drop.style.left = `${Math.random() * 100}vw`;
drop.style.animation = `fall ${0.5 + Math.random() * 1}s linear infinite`;
drop.style.animationDelay = `${Math.random() * 2}s`;
container.appendChild(drop);
// 创建涟漪效果
setTimeout(() => {
setInterval(() => {
const ripple = document.createElement('div');
ripple.className = 'ripple';
ripple.style.left = drop.style.left;
ripple.style.bottom = '0';
container.appendChild(ripple);
// 移除涟漪元素
setTimeout(() => {
ripple.remove();
}, 500);
}, 1000 + Math.random() * 1000);
}, Math.random() * 2000);
}
</script>
</body>
</html>
增强效果的技巧
调整雨滴数量可以改变降雨强度,增加更多雨滴会使效果更密集。修改动画时间和延迟可以创建不同速度的雨滴,模拟真实降雨的不规则性。添加背景模糊或渐变可以增强场景深度感。






