How to add Parallax Scrolling with CSS

Parallax scrolling is when it looks like part of the page are moving over a static background image. It was all the shits a few years ago, and I have to admit I still think it looks super nifty, so naturally I wanted to learn how to do it.

Check out the example I made adding some nice images to one of my favourite poem, Poe’s Annabel Lee.

In the HTML, I created <sections> for each verse of the poem, and in between I added empty <sections class=”parallax” to add the images in between.

Through W3School I found all the CSS properties I need to create the effect. Here is the CSS code:

.parallax{
background-image: url(‘#’) ;
height: 200px;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}

Here is what happens in detail:

  • background-image let’s you define the URL of the image you want to use
  • height defines the height of the image part.
  • background-attachment: fixed makes the image stay static and not scroll with the rest of the page
  • background-position: center aligns the image in the center of its space
  • background-repeat: no-repeat prevents the image from being repeated, which is its default behaviour if you don’t change it
  • background-size: cover will make the image as large as needed to fill the entire background.

As fancy as it looks, from a code perspective parallax scrolling was a lot easier than I thought it would be.

Leave a Reply