CSS Only Parallax

Parallax is rapidly becoming a necessity for any "modern" website, but not all of us feel like mucking around with Javascript all the time.

Tags: Parallax, CSS, Images

Back to Blogs

There are several ways to accomplish this without Javascript. The first ways Google turned up used CSS background images, but I have had issues with Heroku not always displaying those, so deeper we went. These are the two best ways I found to accomplish the task.

With Fixed Images

This is what is used on this site. If you don't have any reason not to use a fixed image, this is probably the easiest way.

Here are the HTML Basics:

<div class="responsive-hero-div">
   <%= image_tag "blog.jpg", class: "responsive-hero-img" %>
</div> <!-- responsive hero div -->

<div class="overlap-responsive-image">
   ...stuff that sits on the image...
</div> <!-- overlap image -->

<div>
   ...anything below that...
</div>

And here's the CSS. This includes some fun trickery for different screen sizes.

.responsive-hero-div {
    width: 100%;
    height: 400px;
    position: fixed;
    overflow: hidden;
  z-index: 0;
}

.responsive-hero-img {
    position: fixed;
    top: 50%;
    height: 100%;
  min-width:100%;
    display: block;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
}

.overlap-responsive-image {
    position: relative;
    width: 100%;
    height: 400px;
    z-index: 15;
}

/* XS Screens */
@media screen and (max-width: 768px) {
  .responsive-hero-img {
    width: auto;
    max-width: 300%;
  }
}

/* Large Screens */
@media only screen and (min-width : 992px) {
  .responsive-hero-div {
    height: 100vh;
  }

  .overlap-responsive-image {
    height: 100vh;
    padding-top: 200px;
  }
}

Without Fixed Images

If you can't or don't want to use fixed images, here's a workaround.

Here's the basic HTML structure:

<div id='container'>
  <div id="group1">
    <div class="background">

    </div> <!-- background -->
    <div class="foreground">

    </div> <!-- foreground -->
  </div> <!-- id #parallax group 1 -->
</div> <!-- id #container -->

And here are the CSS rules:

div {
  box-sizing: border-box;
}

#container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  perspective: 1px;
  overflow-x: hidden;
  overflow-y: scroll;
}

#group1 {
  position: relative;
  transform-style: preserve-3d;
}

.background {
  transform: translateZ(-1px) scale(2);
  height: 425px;
  width: 100%;
  position: absolute;
  top: calc(200px - 50vh);
}

.foreground {
  background-color: white;
  position: absolute;
  top: 425px;
  width: 100%;
}

Short and sweet. See it in action on this website.


Back to Blogs