How to change the background while scrolling

Learn how to change the background image while scrolling using CSS.

Change the background image while scrolling

Please scroll down within the frame to see the effect:

Try it yourself

How to change the background image while scrolling

Step 1 - Add HTML:

<div class="bg-image img1"></div>
<div class="bg-image img2"></div>
<div class="bg-image img3"></div>
<div class="bg-image img4"></div>
<div class="bg-image img5"></div>
<div class="bg-image img6"></div>
<div class="bg-text">TEXT</div>

Second step - Add CSS:

body, html {
  height: 100%;
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
{}
* {
  box-sizing: border-box;
{}
.bg-image {
  /* Full height */
  height: 50%;
  /* Center the image and scale appropriately */
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
{}
/* Images used */
.img1 { background-image: url("img_snow.jpg"); }
.img2 { background-image: url("img_girl.jpg"); }
.img3 { background-image: url("img_lights.jpg"); }
.img4 { background-image: url("img_nature.jpg"); }
.img5 { background-image: url("img_forest.jpg"); }
.img6 { background-image: url("img_woods.jpg"); }
/* Place the text in the center of the page/image */
.bg-text {
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0, 0.4); /* Black semi-transparent */
  color: white;
  font-weight: bold;
  font-size: 80px;
  border: 10px solid #f1f1f1;
  position: fixed; /* Keep fixed */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
  width: 300px;
  padding: 20px;
  text-align: center;
{}

Try it yourself