Parallax example 2

by Richard Hunter

HTML

<div class="content">
  <div class="near panel"></div>
  <div class="base panel"></div>
  <div class="far panel"></div>
</div>
<p>
  For the parallax effect, we want to convey a sense of movement rather than of depth. We want to be able to make two elements of the same size move at different speeds as we scroll.
</p>
<p>
  To achieve this, we employ a clever optical illusion: More distant elements which move slower are scaled up so that they appear at the same size as faster moving elements that are closer.
</p>

SCSS

$perspective: 200;
@function calculateTransform($distance) {
  $left: 50;
  $top: 100;
  $scale: ($perspective - $distance) / $perspective;
  @return translateX($left * $scale * 1px) translateY($top * $scale * 1px) translateZ($distance * 1px) scale($scale);
}

.content {
  perspective: $perspective * 1px;
  perspective-origin: left top;
  width: 200px;
  height: 200px;
  background-color: yellow;
  overflow-y: scroll;
}

.content:before {
  content: '';
  height: 2000px;
  display: block;
}

.panel {
  position: absolute;
  top: 0;
  left: 0;
  transform-origin: left top;
  border: solid 1px black;
  height: 100px;
  width: 100px;
  opacity: 0.3;
}

.base {
  transform: calculateTransform(0);
  background: green;
}

.far {
  transform: calculateTransform(-50);
  background: blue;
}

.near {
  transform: calculateTransform(50);
  background: red;
}