CSSだけでヒーローイメージのセクションにシンプルなパララックス効果

Ads

Result

CSSだけで簡単なパララックス効果を出そう、というもの。既にありふれた情報かもしれませんが。

内容としては3D空間を作り、ヘッダに疑似要素を作って背景画像を設定、z軸に沿ってオブジェクトを遠ざけるよう設定します。

header::before {
   transform: translateZ(-4px);
}
header div {
   transform: translateZ(-2px);
}

また、3D空間の中でフラット描画されるよう、親要素にtransform-styleを設定しておきます。

header {
   transform-style: preserve-3d;
}

これだけだと単に縮小された状態になってしまうのでscaleで戻してあげる必要があります。

scaleで戻すには計算が必要です。Googleの記事では以下の計算法が使われています。

scale = (perspective – distance) / perspective

本Tipsではperspectiveを4、距離(translateZ)を-4pxとしましたので以下の計算でscale値を導き出します。

scale = (4 – (-4))/4 = 2

これを前述したtransformに加えれば元のサイズに戻り、パララックス効果のみを演出する事が出来ます。

header::before {
   transform: translateZ(-4px) scale(2);
}

これで、CSSのみでパララックス効果を出す、というトリックが成立しました。

Ads

css

* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}
html {
	width: 100%;
	height: 100%;
	overflow: hidden;
}
body {
	width: 100%;
	height: 100%;
	font-size: 18px;
	color: #212121;
	perspective: 4px;
	overflow-x: hidden;
	overflow-y: scroll;
}
header {
	width: 100%;
	min-height: 100vh;
	position: relative;
	transform-style: preserve-3d;
}
header::before {
	content: "";
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	display: block;
	background: url("https://source.unsplash.com/1600x900/?nature,water");
	background-size: cover;
	z-index: 0;
	transform: translateZ(-4px) scale(2);
}
header div {
	position: absolute;
	z-index: 1;
	top: 50%;
	padding: 0 30px;
	transform: translateZ(-2px) scale(1.5);
}
header h1 {
	font-size: 4.5rem;
	color: #009688;
}
header h2 {
	font-size: 2.2rem;
}
section {
	width: 100%;
	background: white;
	position: relative;
	z-index: 2;
}
.container {
	margin: auto;
	max-width: 1000px;
	padding: 80px 40px;
}

.container p {
	padding-top: 30px;
	line-height: 1.8;
}

html

<header>
	<div>
		<h1>hoge</h1>
		<h2>hugahuga</h2>
	</div>
</header>

<section>
	<div class="container">
		<h3>foo bar</h3>
		<p>
			Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores harum veritatis nemo magni odio reprehenderit atque, esse animi porro suscipit vero nobis modi quis. Exercitationem quasi beatae, assumenda officia illum sunt. Cum voluptas maiores vitae eius hic inventore deleniti placeat perferendis quam ut nostrum maxime optio voluptatibus ab laboriosam, quia consectetur atque minus?
		</p>

	</div>
</section>

via

今回のTipsは1stwebdesignerにて更に細かく解説されていますので合わせてご参照ください。

Create Simple Parallax Scrolling Effect in Hero Section using Pure CSS

タイトルとURLをコピーしました