How to Change Background Images on Scroll using CSS?

Background images are crucial in web development, significantly enhancing the user experience. Using background images on a webpage can effectively showcase a brand or convey specific messages. Here, we will explore how to change background images on scroll using CSS.

Approach

  • The HTML includes a span element and three div elements with the class .bg-image and unique classes.
  • The span element is styled with position: fixed to keep it in a fixed position within the viewport, providing a constant reference text as the user scrolls through the background images.
  • The .bg-image class is defined with properties to set the background image’s position, size, repeat behavior, and attachment to the viewport. This ensures each background image covers the entire viewport and remains fixed during scroll.
  • As the user scrolls down the page, each div with the class .bg-image takes up the full viewport height (100vh), causing the background images to change sequentially while the fixed text remains in place.

Example: The example below shows how to change background images on scroll using CSS.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        body,
        html {
            height: 100%;
            margin: 0;
            font-family: Arial, Helvetica, sans-serif;
        }

        .bg-image {
            height: 100vh;
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
            background-attachment: fixed;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 1.5em;

        }

        span {
            position: fixed;
            top: 30vh;
        }

        .img1 {
            background-image:
url('https://media.w3wiki.net/wp-content/uploads/20230416201559/DevOps-Roadmap.webp');
        }

        .img2 {
            background-image:
url('https://media.w3wiki.net/wp-content/uploads/20231207165628/Full-Stack-Developer-Roadmap.webp');
        }

        .img3 {
            background-image:
url('https://media.w3wiki.net/wp-content/uploads/20240308154942/web-(1).jpg');
        }

        .img1_data {
            color: rgb(34, 228, 57);
            margin-left: 10rem;
            margin-top: 15rem;
        }
    </style>
</head>

<body>
    <span class="img1_data">
        w3wiki is a leading platform that
        provides computer science resources and
        coding challenges for programmers and
        technology enthusiasts, along with
        interview and exam preparations for
        upcoming aspirants.
    </span>
    <div class="bg-image img1">
    </div>
    <div class="bg-image img2">
    </div>
    <div class="bg-image img3">
    </div>
</body>

</html>

Output: