Change the background image on scroll using CSS

We can change the background image of the webpage on scroll without changing the foreground contents.

1. Create HTML

Create seven <div> tags with the following classes:

<div class=”image one”></div>

<div class=”image two”></div>

<div class=”image three”></div>

<div class=”image four”></div>

<div class=”image five”></div>

<div class=”image six”></div>

<div class=”image seven”></div>

<div class=”content”>W3DOCS</div>

2. Add CSS

  • Set the height of the body to 100% and the margin to 0.
  • Specify the font family names with the font-family property.
  • Center the images with the background-position property.
  • Set the background-repeat property to “no-repeat” so as the images won’t be repeated.
  • Set the background-size to “cover” to scale the images as large as possible to cover all the background area.
  • Add links of the images with the background-image property.
  • Style the content giving it a border and setting the width and height of it.
  • Set the position to “fixed” so as it will be fixed while scrolling.
  • Style the text with the color, font-weight and font-size properties.
  • Use the “translate” value of the transform property, where the first value will move the element to the left (negative values to the left). The second value will move it up (negative values up).
  • Center the content with the help of the text-align property.
  • Give padding to create space on all sides of an element’s content.
  • Add the z-index which specifies its order inside a stacking context.
  • Specify the left and top margin edges with the left and the top properties.
  • Give a background color to the content with the background-color property. We use the RGB value.
Sample Code
body,
html {
  height: 100%;
  margin: 0;
  font-family: Helvetica, sans-serif;
}
.image {
  height: 50%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
.one {
  background-image: url("https://images.unsplash.com/photo-1523240795612-9a054b0db644?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80")
}
.content {
  background-color: rgb(0, 0, 0, 0.5);
  color: #fff0c2;
  font-weight: bold;
  font-size: 60px;
  border: 8px solid #000000;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
  width: 270px;
  padding: 50px;
  text-align: center;
}

Leave a comment

Your email address will not be published. Required fields are marked *