スマホ用のサイトを制作中にiPhoneのSafariで背景画像のposition: fixed;が効かなかったので、それの対処法の備忘録。
この「ああああああ」のボックスが上のメインビジュアルの上を移動していって欲しい。
かつメインビジュアルは固定された状態。
これがスマホ(iPhone)で見た場合SafariもChromeも一瞬画像の下に「ああああ」のボックスが潜り込んでします。
こんな感じで「あああああ」がメインビジュアルの下にいってしまいます。
ただし、スワイプ中にだけ起こって、指を離すとちゃんとメインビジュアルの上に「あああああ」のボックスがきます。
結局なにがダメだったかというと、メインビジュアルのdivにz-indexが指定してなかったことが原因でした。
ダメだったcss
#main_image { background-image: url(images/bg1.jpg); background-repeat: no-repeat; background-size: cover; width: 100%; height: 500px; position: fixed; top: 0; left: 0; } #contents { position: relative; margin: 500px 0 0; background: #fff; width: 100%; z-index: 2; height: 2000px; }
正しく動いたcss
10行目にz-indexを指定
#main_image { background-image: url(images/bg1.jpg); background-repeat: no-repeat; background-size: cover; width: 100%; height: 500px; position: fixed; top: 0; left: 0; z-index: -1; //←これを追加した } #contents { position: relative; margin: 500px 0 0; background: #fff; width: 100%; z-index: 2; height: 2000px; }
ちなみにこちらはhtml
<body> <div id="main_image"></div> <div id="contents"> あああああ </div> </body>