Bỏ qua, tới nội dung chính

Tuyết rơi

Những bông tuyết nhẹ nhàng rơi trên nền trời đêm, dùng CSS và JS thuần.

Dịp: Giáng Sinh

Xem toàn màn hình

Mã nguồn

<div id="snow" aria-hidden="true"></div>
html, body { height: 100%; margin: 0; }
body { background: linear-gradient(#0f1b3d, #2b4a7c); overflow: hidden; }
#snow { position: fixed; inset: 0; pointer-events: none; }
.flake {
  position: absolute;
  top: -10px;
  border-radius: 50%;
  background: #fff;
  opacity: 0.85;
  animation: fall linear infinite;
}
@keyframes fall {
  to { transform: translate3d(var(--drift), 110vh, 0); }
}
(function () {
  var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
  var box = document.getElementById('snow');

  function snow() {
    box.innerHTML = '';
    if (reduceMotion.matches) return;

    for (var i = 0; i < 80; i++) {
      var flake = document.createElement('span');
      var size = 2 + Math.random() * 4;
      flake.className = 'flake';
      flake.style.left = Math.random() * 100 + '%';
      flake.style.width = flake.style.height = size + 'px';
      flake.style.animationDuration = 6 + Math.random() * 8 + 's';
      flake.style.animationDelay = -Math.random() * 14 + 's';
      flake.style.setProperty('--drift', (Math.random() * 80 - 40) + 'px');
      box.appendChild(flake);
    }
  }

  snow();
  reduceMotion.addEventListener('change', snow);
})();

Giấy phép MIT — dùng thoải mái, kể cả cho dự án thương mại.

Nhớ thêm xử lý prefers-reduced-motion khi đem hiệu ứng này vào trang của bạn, để người dùng không thích chuyển động vẫn thấy dễ chịu.

Mỗi bông tuyết là một phần tử nhỏ được tạo bằng JS với kích thước, tốc độ và độ lệch ngẫu nhiên; chuyển động do CSS animation đảm nhiệm nên rất nhẹ.

Khi hệ điều hành của người xem bật prefers-reduced-motion, hiệu ứng tự tắt và không có bông tuyết nào được tạo.