How do I create a CSS-only reveal effect on scroll?

Creating a CSS-only Reveal Effect on Scroll

In this blog post, we will learn how to create a CSS-only reveal effect when the user scrolls down the page. This effect can be used to enhance the user experience on your website by creating a sense of interaction and engagement. We’ll achieve this effect using pure CSS, without any JavaScript.

Here’s a step-by-step guide on how to create a CSS-only reveal effect on scroll.

Step 1: HTML Structure

First, let’s create the HTML structure for our reveal effect. We’ll use a simple example with a few text elements inside a container element.

<!-- HTML -->
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="container">
    <h2 class="reveal-on-scroll">Reveal Me!</h2>
    <p class="reveal-on-scroll">This paragraph will be revealed when you scroll down.</p>
    <p class="reveal-on-scroll">So will this one!</p>
  </div>
</body>
</html>

Step 2: Basic CSS

Now, let’s add some basic styles to our elements. We’ll give the container some padding and set a max-width to limit its size.

/* CSS */
.container {
max-width: 600px;
margin: 0 auto;
padding: 2rem;
}

Step 3: Reveal Effect CSS

To create the reveal effect, we’ll use CSS animations and the ‘@keyframes’ rule. We’ll start by setting the initial styles for the elements with the ‘reveal-on-scroll’ class.

/* CSS */
.reveal-on-scroll {
opacity: 0;
transform: translateY(20px);
animation: reveal 1s ease-in-out forwards;
animation-fill-mode: both;
visibility: hidden;
}

Next, we’ll define the ‘reveal’ animation using the ‘@keyframes’ rule. The animation will change the element’s opacity and position when the user scrolls down the page.

/* CSS */
@keyframes reveal {
0% {
opacity: 0;
transform: translateY(20px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}

Step 4: Triggering the Reveal Effect

To trigger the reveal effect on scroll, we’ll use the ‘:target’ pseudo-class in our CSS. Add an ID to each element with the ‘reveal-on-scroll’ class, and create an anchor link that targets each ID.

<!-- HTML -->
<div class="container">
  <a href="#reveal1"></a>
  <h2 class="reveal-on-scroll" id="reveal1">Reveal Me!</h2>
  <a href="#reveal2"></a>
  <p class="reveal-on-scroll" id="reveal2">This paragraph will be revealed when you scroll down.</p>
  <a href="#reveal3"></a>
  <p class="reveal-on-scroll" id="reveal3">So will this one!</p>
</div>

Now, update the CSS to trigger the reveal effect when the elements are targeted.

/* CSS */
.reveal-on-scroll:target {
animation-play-state: running;
visibility: visible;
}

That’s it! You’ve now created a CSS-only reveal effect that triggers when the user scrolls down the page. Feel free to customize the animation properties to create your desired effect.

Got question?

Submit it here

© All rights reserved.