This code snippet allows you to create a delightful falling heart animation on your web page. The animation is implemented using CSS and JavaScript. Hearts will fall from the top of the screen to the bottom with a smooth motion. The animation duration and position of the hearts are randomized to create a dynamic effect.
Simply include this code in your HTML file, and you’ll have a charming falling heart animation to enhance your website’s visual appeal.
How to Create Falling Heart Animation in CSS
Create the HTML structure as follows:
<body> <h1>Heart Rain Animation</h1> </body>
Style using the following CSS styles for falling heart animation:
@import url("https://fonts.googleapis.com/css2?family=Pacifico:wght@200;400;600&display=swap"); @import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"); * { box-sizing: border-box; } .cd__main{ background: pink !important; font-family: 'Pacifico', cursive !important; min-height: 450px; } body { background-color: pink; display: flex; align-items: center; justify-content: center; font-family: 'Pacifico', cursive; margin: 0; min-height: 100vh; } .heart { position: fixed; font-size: 1.5rem; top: -1vh; transform: translateY(0); animation: fall 3s linear forwards; } @keyframes fall { from { transform: translateY(0vh) translateX(-10vw); } to { transform: translateY(105vh) translateX(10vw); } }
Add the following JavaScript function:
function createHeart() { const heart = document.createElement('div'); heart.classList.add('heart'); heart.style.left = Math.random() * 100 + "vw"; heart.style.animationDuration = Math.random() * 2 + 3 + "s"; heart.innerText = '💗'; document.body.appendChild(heart); setTimeout(() => { heart.remove(); }, 5000); } setInterval(createHeart, 300);
That’s all! hopefully, you have successfully integrated this falling hearts animation into your project. If you have any questions or suggestions, feel free to comment below.