Fixed Background Scrolling Effect using CSS

A lot of dynamic effects can be given in web projects using just CSS. One such effect is keeping background fixed as foreground moves on scrolling. It can be achieved using a single CSS property - background-attachment.

Look at the following demo in which the backgrounds of different sections of a web page are fixed while their contents move on scrolling.

The code to create the effect shown in the demo is explained below in steps.

The Structure

The HTML consists of five sections. The first, third and fifth sections are given images as background that do not scroll when their contents scroll, and the second and fourth sections are given background colors. All these sections are wrapped within a div.

The Styling

Step 1

In the demo, I wanted the height of the first, third and fifth sections same as the height of the viewport. For this, height: 100% is given to the three sections and all their ancestors (.fixed-bg -> .wrapper -> body -> html).

CSS

html,body{height:100%;}.wrapper{height:100%;}.fixed-bg{height:100%;}

If you give a fixed height to these three sections, then there is no need to give height to their ancestors.

Step 2

Background images are given to the first, third and fifth sections and background color to the remaining two sections.

The background images are given the respective background properties to make them not repeatable, cover the background area and positioned at the center. Giving background-attachment: fixed prevents them from scrolling with the content. This is the key step for our scrolling effect.

Conclusion

Backgrounds have always been an indispensable part of web pages. Any web page can be made more lively by doing just a slight change in the way its background appears. For example, you can give a video as background or can apply various effects and animations to it. Apart from making the background fixed as shown in this post, you can give lots of parallax effects in your web pages which make the background scroll at a slower speed as compared to its content. Come up with your own ideas on applying this effect.