Signup/Sign In
PUBLISHED ON: AUGUST 24, 2021

How to change background images on scroll with CSS?

One interesting thing about designing a page is that we can add our innovation to make the web page more beautiful and attractive. We just need to add some CSS properties.

In this tutorial, we are going to change the background image of the webpage on scroll without changing the foreground contents.

Changing background image on scroll

Add multiple empty <div> element on the web page. To each div add a background-image property.

Add background-size, background-position and background-repeat properties to the background image.

Set the height of each <div> element. Add some text in the foreground and add position:fixed to it. Use other properties like font-size padding, width, etc to customize.

Example: Changing background image on scroll with CSS

In this example, the background image changes on scroll whereas the text remains fixed at a position.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
    body, html {
	  height: 100%;
	  margin: 0;
	}
   .bg {
      height: 50%;
	  background-position: center;
	  background-repeat: no-repeat;
	  background-size: cover;
   }
   /* Adding image to each div */
    .image1 {
	  background-image: url("https://s3.studytonight.com/tutorials/uploads/pictures/1629719426-.jpeg");
	}
	.image2 {
	  background-image: url("https://s3.studytonight.com/tutorials/uploads/pictures/1629719465-.jpeg");
	}
	.image3 {
	  background-image: url("https://s3.studytonight.com/tutorials/uploads/pictures/1629719495-.jpeg");
	}
	.image4 {
	  background-image: url("https://s3.studytonight.com/tutorials/uploads/pictures/1629719528-.jpeg");
	}
	.text {
	   font-size: 30px;
	   text-align: center;
	   position: fixed;
	   top: 30%;
	   left: 30%;
	   width: 40%;
	   padding: 16px;
	   background-color: rgba(0,0,0,0.5)
	   background-color: rgb(0,0,0); /*if image does not loads */
	   color: white;
	}
</style>
</head>
<body>    
    <div class="bg image1"></div>
	<div class="bg image2"></div>
	<div class="bg image3"></div>
	<div class="bg image4"></div>
	<div class="text">
	   <h3>Scroll the page </h3>
	   <p> Image changes on scroll </p>
	</div>
</body>
</html>

Output

Here is the output of the above example.

change background image on scroll

Example: Changing background image on scroll

In this example, we have added a parallax effect to change the image on scroll. To add parallax effect, use background-attachment:fixed.

Conclusion

In this tutorial, we have learned to change images on scroll. To do so use the background property to add an image and other CSS properties. Here in the example, we have also added parallax effect on image change.



About the author: