スクロールしたときに背景だけスクロール速度が変わるようなパララックスは JavaScript で実装するのが一般的ですが、CSS で要素を 3D 空間上に配置する方法を使えば JavaScript なしでパララックスを実装することができます。
<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
の値を指定すると元のサイズに見せかけることができます。
さいごに
ここで紹介したパララックスを使ってポートフォリオを作りました。
Next.js + Vercel (Now) でポートフォリオ作りました👌https://t.co/N1LYdqxIFS pic.twitter.com/g5xu0wFbsF
— やまいも (@yarnaimo) April 27, 2020