0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LPとかでよく見るあれがやりたい(position: sticky;)

0
Last updated at Posted at 2019-11-18

この記事のターゲット

  • あれがやりたんだよあれが
  • stickyってなんだろう
  • いいから動くものをくれ

最終成果物

これです。
LPとかでよくみますね。

sticky.gif

実装

土台になるhtmlの用意

さっくりと。

index.html
<!DOCTYPE html>
<html lang ="ja">
<head>
    <link rel="stylesheet" href="../css/sticky.css">
</head>
<body>
    <main>
        <section class="block section-first"><h2>First</h2></section>
        <section class="block section-second"><h2>Second</h2></section>
        <section class="block section-thrid"><h2>Thrid</h2></section>
    </main>
</body>
</html>

要素にstickyを適用

まずは気にせず動かしてみましょう。

sticky.css

h2 {
	font-family: 'Century';
}

.block {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 100%;
	height: 100vh; 
	position: -webkit-sticky;
	position: sticky;
	top: 0;
}

.section-first {
	background: rgb(52, 225, 255);
}

.section-second {
	background: rgb(79, 183, 214);
}

.section-thrid {
	background: rgb(45, 110, 141);
}

カンタンに解説

h2とsection-firstとかはただの装飾なのでまぁ置いておいて。
大事なのはblockクラスですね。

position: sticky;

これが大事です。
そもそもstickyってどんな意味でしょう。

日本語訳すると「粘着性」です。
そう言われるとわからなくもないです。
通常のスクロールで上に行かず画面に張り付いてるイメージってことでしょうかね。
これを指定したことで準備が整いました。
ただし、これだけでは例のあれにはなりません。
どこに粘着させるかを指定しないとただただ上にスクロールされるだけです。

top: 0;

ということでtopを0に固定することで粘着させます。
この値を変えるだけでいろんな高さに粘着させることができるので試してみてください。

まとめ

なんだかシャレオツ!
普通にスクロールさせるよりもコンテンツとコンテンツの境目がはっきりしてより伝わりやすくなりますね。
とはいえ過剰なスクロールジャックは反感を買う可能性もあるのでやり過ぎ厳禁。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?