Dynamic and interactive website design is gaining popularity day by day.
One of the latest trends in website design is to change the background image as the user scrolls down the page.
In this tutorial, we will discuss how to change background images on scroll with CSS.
CSS Properties for Background Image
Before diving into the implementation, let’s have a quick look at the CSS properties related to background images.
- background-image: sets the background image for an element.
- background-position: sets the position of the background image.
- background-size: sets the size of the background image.
- background-repeat: sets if and how a background image will repeat.
Implementation
To change the background image on scroll, we need to set multiple background images for different sections of the page and change them as the user scrolls down.
Step 1: HTML Markup
Create a div for each section of the page with a unique id and set its background image using the CSS background-image property.
<div id="section1" class="section"> <h2>Section 1</h2> <p>Content goes here...</p> </div> <div id="section2" class="section"> <h2>Section 2</h2> <p>Content goes here...</p> </div> <div id="section3" class="section"> <h2>Section 3</h2> <p>Content goes here...</p> </div>
Step 2: CSS Styles
Define the CSS styles for the .section class and set the background image for each section using the #section1, #section2, and #section3 id selectors.
.section {
height: 100vh;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
#section1 {
background-image: url(image1.jpg);
}
#section2 {
background-image: url(image2.jpg);
}
#section3 {
background-image: url(image3.jpg);
}
Step 3: JavaScript
Use JavaScript to detect the scroll position and change the background image accordingly.
We can use the window.scrollY property to get the current vertical scroll position and add an event listener for the ‘scroll’ event to trigger the change in background image.
var sections = document.querySelectorAll('.section');
var currentSection = 0;
window.addEventListener('scroll', function () {
var scrollPosition = window.scrollY;
for (var i = 0; i < sections.length; i++) {
var sectionTop = sections[i].offsetTop;
var sectionBottom = sectionTop + sections[i].offsetHeight;
if (scrollPosition >= sectionTop && scrollPosition < sectionBottom) {
currentSection = i;
break;
}
}
document.body.style.backgroundImage = `url(${currentSection + 1}.jpg)`;
});
Conclusion
In conclusion, changing the background image on scroll is a great way to enhance the user experience on a website.




