How to create alternate fixed and scroll backgrounds with no javascript, but just the help of the CSS background-attachment property set on Fixed.

These days we see a lot of parallax effects in web projects. You can achieve some dynamic results with CSS only, without affecting the website performance. Unless you have to use parallax on background images to make your client happy - which sometimes happens. All you need to learn is how the CSS background-attachment property works. Let's build this snippet together ;)

Demo images from Unsplash.

👋 Important: this experiment is built using the CodyHouse Framework.

Creating the structure

The HTML is quite basic: we alternated <section> elements with a .cd-section--bg-fixed class - used for the sections with fixed backgrounds - with sections with plain backgrounds.

<main> <section class="cd-section cd-section--bg-fixed"> <!-- section content here --> </section> <section class="cd-section"> <!-- section content here --> </section> <!-- other sections here --> </main>

Adding style

When I was thinking about how to achieve this effect, my first thought was to play with JavaScript: maybe I should create an element in position fixed, and use it to change the background image while the user scrolls. Felt too complicated though.

I hadn't considered the Fixed value of the CSS background-attachment property. By default the background-attachment value is Scroll, meaning that the background scrolls along with the element. BUT if you set it to be Fixed, the background behaves as a fixed positioned element: it moves with regards to the viewport.

That's it! Few lines of CSS and we have a nice template suitable for long one-page designs ;)