7
8

More than 3 years have passed since last update.

[CSS] JSを使わずにパララックスを実装する【3D】

Last updated at Posted at 2020-04-28

スクロールしたときに背景だけスクロール速度が変わるようなパララックスは JavaScript で実装するのが一般的ですが、CSS で要素を 3D 空間上に配置する方法を使えば JavaScript なしでパララックスを実装することができます。

b.gif


<div class="container">
  <div class="background">Background (z: -800px)</div>
  <div class="content">Content (z: 0px)</div>
</div>
.container {
  width: 100%;
  height: 100vh;
  overflow-x: hidden;
  overflow-y: auto;
  perspective: 800px;
}

.background {
  z-index: -1;
  width: 200px;
  height: 200px;
  margin: 60px auto;
  transform: translateZ(-800px) scale(2);

  background: hsl(39, 97%, 63%);
  color: white;
}

.content {
  position: relative;
  width: 320px;
  height: 640px;
  margin: 0 auto;

  background: hsl(175, 61%, 77%);
  color: white;
}

解説

Container

まず 3D 空間の基準となるコンテナ要素を作ります。

.container {
  width: 100%;
  height: 100vh;
  overflow-x: hidden;
  overflow-y: auto;
  perspective: 800px;
}
  • ここでは 100% x 100vh
  • overflow-y: auto でスクロールされるようにする
  • perspective プロパティで空間の奥行きを指定する (perspective: 800px だと 800px 手前の場所から見ている感じになる)

Background

次に背景。

.background {
  width: 160px;
  height: 160px;
  margin: 80px auto;
  transform: translateZ(-800px) scale(2);

  background: hsl(39, 97%, 63%);
  color: white;
}
  • translateZ で z 軸方向の位置を指定する (ここでは基準のコンテナより 800px 奥に配置)

z 軸方向の位置が奥に行くほど見かけ上のサイズが小さくなりますが、scale(z軸方向の位置) / -(perspective) + 1 の値を指定すると元のサイズに見せかけることができます。

さいごに

ここで紹介したパララックスを使ってポートフォリオを作りました。

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8