(CSS) Make a background image scroll slower than everything else

user4626554 picture user4626554 · Mar 24, 2015 · Viewed 81.5k times · Source

here is is my CSS code for the body:

body {
  padding: 0;
  margin: 0;
  background-image: url("../images/background.jpg");
  background-repeat: no-repeat;
  background-color: grey; 
  background-size: 100%;
}

What I want to do is make it so that the image scrolls slower than everything else on the page to make a simple parallax effect. I've looked online and all of the examples I've seen are much more complicated than what I want.

Answer

Neo picture Neo · Jun 10, 2016

I stumbled upon this looking for more flexibility in my parallax speed that I have created with pure CSS and I just want to point out that all these people are wrong and it is possible with pure CSS It is also possible to control the height of your element better.

You will probably have to edit your DOM/HTML a bit to have some container elements, in your case you are applying the background to the body which will restrict you a lot and doesn't seem like a good idea.

http://keithclark.co.uk/articles/pure-css-parallax-websites/

Here is how you control the height with Viewport-percentage lenghts based on screen size:

https://stanhub.com/how-to-make-div-element-100-height-of-browser-window-using-css-only/

  .forefront-element {
    -webkit-transform: translateZ(999px) scale(.7);
    transform: translateZ(999px) scale(.7);
    z-index: 1;
  }

  .base-element {
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
    z-index: 4;
  }

  .background-element {
    -webkit-transform: translateZ(-999px) scale(2);
    transform: translateZ(-999px) scale(2);
    z-index: 3;
  }

Layer speed is controlled by a combination of the perspective and the Z translation values. Elements with negative Z values will scroll slower than those with a positive value. The further the value is from 0 the more pronounced the parallax effect (i.e. translateZ(-10px) will scroll slower than translateZ(-1px)).

Here is a demo I found with a google search because I know there are a lot of non-believers out there, never say impossible:

http://keithclark.co.uk/articles/pure-css-parallax-websites/demo3/