How to Create a Fade-In Effect on Page Load with CSS and JavaScript

Adding a fade-in animation when a page or element loads can make your site look smoother and more professional. It’s a subtle touch that enhances user experience — and the best part? You don’t need a heavy library to do it.

Let’s build this effect step by step using just HTML, CSS, and a bit of JavaScript.


🧱 Step 1: Basic HTML Structure

We’ll create a simple section that fades in as the page loads:

<div class="fade-in-section">
  <h1>Welcome to Dev Junior School</h1>
  <p>This content will fade in smoothly when the page loads.</p>
</div>

🎨 Step 2: CSS for Fade-In Animation

.fade-in-section {
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 1s ease-out, transform 1s ease-out;
}
.fade-in-section.visible {
  opacity: 1;
  transform: translateY(0);
}

✔️ Explanation:

  • opacity: 0 makes the element invisible initially
  • transform: translateY(20px) moves it slightly down
  • When the .visible class is added, it animates to full opacity and its original position

⚙️ Step 3: JavaScript to Trigger the Animation on Load

window.addEventListener("DOMContentLoaded", () => {
  document.querySelector(".fade-in-section").classList.add("visible");
});

This waits for the HTML to fully load before adding the .visible class, triggering the animation.


✅ Final Result

As soon as the page loads, the content fades in smoothly. You can apply this to:

  • Hero sections
  • Call-to-actions
  • Titles or paragraphs
  • Any element that should animate in

🧠 Bonus Tip: Reuse the Animation

You can apply this effect to multiple elements by giving them the same class:

<div class="fade-in-section">Box 1</div>
<div class="fade-in-section">Box 2</div>

And loop through them in Javascript:

document.querySelectorAll(".fade-in-section").forEach(el => {
  el.classList.add("visible");
});

Leave a Comment