CSS: parallax-like effect: background image is static while page scrolls

In short, setting one CSS property, background-attachment: fixed, can form the basis of a parallax effect.

The value of fixed means that the background image of an element should remain in the same spot relative to the viewport instead of being in the same spot relative to the rest of the page. This means, for example, the part of the image drawn 100px from the top of the user’s monitor and 100px from the left of the user’s monitor will remain always remain 100px from the top and 100px from the left, even if the user scrolls up or down the page.

Code:

<style>
#background-attachment-example-1 {
  height: 200px;
  border: 1px solid black;
  background-image: url('https://www.css-daily.com/wp-content/uploads/2018/10/housey.png');
  background-repeat: repeat;
  background-attachment: fixed;
}
</style>
<div id="background-attachment-example-1"></div>

Result:

Try scrolling to see the effect in the image above.

Leave a Reply

Your email address will not be published.

Color scheme: