LoginSignup
15
6

More than 5 years have passed since last update.

iOSのバウンススクロール時の背景色を上下で異なる色に変える

Last updated at Posted at 2018-05-14

iOSのバウンススクロール時の背景色を上下で異なる色に変える

何がしたいのか

Before

start.gif

これを

After

after.gif

こうしたい

Beforeコード

ひとまず全て書き出します。

<!doctype html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>Title</title>
    <style>
        /* 表示調整用スタイル */
        * {
            padding: 0;
            margin: 0;
        }
        html, body, .container {
            height: 100%;
        }
        .header, .main, .footer {
            display: block;
        }
        .header {
            height: 50px;
            background-color: lightgreen;
        }
        .main {
            min-height: calc(100% - 100px);
            background-color: white;
        }
        .footer {
            height: 50px;
            background-color: lightgray;
        }
    </style>
</head>
<body>
<div class="container">
    <header class="header">header</header>
    <main class="main">main contents...</main>
    <footer class="footer">footer</footer>
</div>
</body>
</html>

テスト用コンテンツの配置と、コンテンツの高さを調整しています。

CSSを調整していきますので、CSS部分のみ切り出して再度見ておきます。

/* 表示調整用スタイル */
* {
    padding: 0;
    margin: 0;
}
html, body, .container {
    height: 100%;
}
.header, .main, .footer {
    display: block;
}
.header {
    height: 50px;
    background-color: lightgreen;
}
.main {
    min-height: calc(100% - 100px);
    background-color: white;
}
.footer {
    height: 50px;
    background-color: lightgray;
}

ここで重要なのは.header.main.footerにそれぞれ背景色が指定されているということです。

Afterコード

/* 表示調整用スタイル */
* {
    padding: 0;
    margin: 0;
}
html, body, .container {
    height: 100%;
}
.header, .main, .footer {
    display: block;
}
.header {
    height: 50px;
    background-color: lightgreen;
}
.main {
    min-height: calc(100% - 100px);
    background-color: white;
}
.footer {
    height: 50px;
    background-color: lightgray;
}
/* バウンススクロール時のカラースタイル */
body::before,
body::after {
    content: "";
    display: block;
    width: 100%;
    height: 50%;
    position: fixed;
    left: 0;
    z-index: -1;
}
body::before {
    top: 0;
    background-color: lightgreen;
}
body::after {
    bottom: 0;
    background-color: lightgray;
}

差分は/* バウンススクロール時のカラースタイル */というコメント以降の記述のみです。

要点は

  • bodyに疑似要素を設定し、上半分を.headerと同じ色に、下半分を.footerと同じ色に設定しfixedで固定配置
  • 疑似要素にz-index: -1;を指定し、.header.mainよりも後ろに回り込ませる
  • bodyは背景色を指定せず(透明)、疑似要素は可視化

です。

これにより、バウンススクロールした時に固定配置された疑似要素が見えるようになり、また上下で異なる色が設定されているように見えます。

バウンススクロールが50%を超えた場合に色の境界が見えてしまいますが、50%を超えることはほぼないと考えています。

最後に

(こんなことやりたい人いる・・・?)

15
6
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
15
6