When 2 or more layers are moving at different speeds in the same or opposite direction it creates a sort of gliding effect. This effect is known as parallax. There are many ways we can achieve the parallax effect using CSS.
What is parallax?
First, You should know what is parallax. The parallax effect attempts to replicate this experience of foreground objects moving faster than their counterparts from the background. Understand it better: When we are in the car, we see trees, houses, etc. which passes through our eyes in front. Things which are closest to you and the road itself quickly moves into a blur, while the things that are away, the move slowly.
CSS in 3D
how to use this effectively :
- Set up a containing element to scroll with overflow-y: scroll (and probably overflow-x: hidden).
- To that same element apply a perspective value, and a perspective-origin set to the top left, or 0 0.
- To the children of that element apply a translation in Z and scale them back up to provide parallax motion without affecting their size on the screen.
Adjusting scale for perspective
Pushing the child element back will cause it to get smaller proportional to the perspective value. You can calculate how much it will need to be scaled up with this equation: (perspective – distance) / perspective. Since we most likely want the parallaxing element to parallax but appear at the size we authored it, it would need to be scaled up in this way, rather than being left as is.
In the case of the above code, perspective is 1px, and the parallax-child’s Z distance is -2px. This means that the element will need to be scaled up by 3x, which you can see is the value plugged into the code: scale(3).
For any content that doesn’t have a translateZ value applied, you can substitute a value of zero. This means the scale is (perspective – 0) / perspective, which nets out at a value of 1, which means that it’s been scaled neither up or down. Quite handy, really.