scroll-snap-type
最近のウェブサイトとかでよくある1つのセクションをスクロールでスライドしながら表示していくみたいなウェブサイトを作りたい場合、そういうライブラリを使ったりするっていうのもあるが普通にCSSだけで作る事もできるっぽいのでやってみた
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="./style.css" />
</head>
<body>
<div id="container">
<div id="box1" class="box bg-1">box1</div>
<div id="box2" class="box bg-2">box2</div>
<div id="box3" class="box bg-3">box3</div>
<div id="box4" class="box bg-4">box4</div>
<div id="box5" class="box bg-5">box5</div>
</div>
</body>
</html>
セクションで表示するのを<div class=box
>でいくつか設置する。あとはCSSでこれをスクロールスタイルを定義してそういうふうに表示されるようにする
style.css
info各セクションの装飾のCSSは省略
html, body {
margin: 0;
}
#container {
overflow: auto;
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
scroll-snap-type: y mandatory;
scrollbar-width: none;
-ms-overflow-style: none;
}
#container::-webkit-scrollbar {
display: none;
}
.box {
width: 100vw;
min-height: 100vh;
align-content: center;
text-align: center;
scroll-snap-align: start;
font-size: 3em;
font-weight: bold;
}
各セクションでscroll-snap-alignを設定してその親要素でscroll-snap-typeを設定する。今回は普通に縦にしているのでy mandatoryにしている。実行すると以下のような感じになる
また、今回は各セクションにidをふっているのでURLハッシュフラグメントで各要素に移動させたりもできるがもし動的にJavaScriptを使って移動させたい場合とかには
document.querySelector("idなど").scrollIntoView({ behavior: "smooth" });
などを使ってJavaScriptを使って移動させたりなども出来るっぽい
余談
一応、jsfiddleのデータが消えた場合とかのためにGithubにコードだけ置いておく
https://gist.github.com/kinjouj/f8d09c3251b67695543f80d33efcd4fa