Author: | Ljupce-Atanasov |
---|---|
Views Total: | 172 views |
Official Page: | Go to website |
Last Update: | December 23, 2024 |
License: | MIT |
Preview:

Description:
Create a beautiful, performant, and customizable snowfall animation using only CSS/CSS3 and a small amount of JavaScript—just over 30 lines. No SVG, Images, and Canvas elements required.
The snowfall effect generates snowflakes dynamically based on viewport dimensions. Each snowflake receives randomized properties that control its size, position, opacity, and animation timing. This creates an organic, natural-looking snow effect that works perfectly across devices.
How to use it:
1. Create a container element for the snowfall animation:
<div class="snowfall-animation"></div>
2. Make the container span the full page:
.snowflake-area { position: relative; width: 100%; height: 100%; z-index: 10; }
3. Style the individual snowflakes using CSS:
.snowflake { position: absolute; top: -20%; aspect-ratio: 1; border-radius: 50%; background-color: snow; animation: snowfall 10s linear infinite; z-index: 10; }
4. Define the snowfall animation using the @keyframes
rule. This controls the vertical movement and rotation of the snowflakes. The sway
animation adds a subtle horizontal movement.
@keyframes snowfall { 0% { transform: translateY(0) rotate(0); } 100% { transform: translateY(110vh) rotate(360deg); } } @keyframes sway { 0%, 100% { transform: translateX(calc(-1 * var(--sway-amplitude))); } 50% { transform: translateX(var(--sway-amplitude)); } }
5. Include the following JavaScript code in your project. This script calculates the number of snowflakes based on screen width and then creates and styles each snowflake dynamically.
const getSnowflakeCount = () => { let width = window.screen.width; if (width < 768) return 1000; if (width < 1024) return 1500; return 2000; }; const letItSnow = () => { const snowflakeArea = document.querySelector(".snowfall-animation"); for (let i = 0; i < getSnowflakeCount(); i++) { const snowflake = document.createElement("div"); snowflake.classList.add("snowflake"); const randomSize = Math.random() * 4 + 1; const randomDuration = Math.random() * 11 + 4; const randomXPosition = Math.random() * 100; const randomDelay = Math.random() * 6; const randomOpacity = Math.random() * 0.2 + 0.4; snowflake.style.left = `${randomXPosition}%`; snowflake.style.animationDuration = `${randomDuration}s`; snowflake.style.width = `${randomSize}px`; snowflake.style.animationDelay = `${randomDelay}s`; snowflake.style.opacity = `${randomOpacity}`; snowflakeArea.appendChild(snowflake); } }; letItSnow();