CodyHouse Framework + Components are featured on Product Hunt! Join the discussion →

Alternate Fixed & Scroll Backgrounds

Alternate Fixed & Scroll Backgrounds

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

Nucleo logo Sponsored by Nucleo, a powerful icon manager for web designers

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 ;)

.cd-section {
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}

.cd-section--bg-fixed {
  min-height: 100vh;
  background-attachment: fixed;
}

/* backgrounds */
.cd-section:nth-child(1) {
  background-image: url("../img/cd-background-1.jpg");
}

.cd-section:nth-child(2) {
  background-color: var(--cd-color-2);
}

.cd-section:nth-child(3) {
  /* background image here */
}

/* all other background images */

💌 Join our newsletter

Be the first to know when we ship something cool!

Project duplicated.