LoginSignup
3
4

More than 3 years have passed since last update.

【注意!】iOSでは背景画像が動いてしまう問題について

Posted at

はじめに

簡単なwebページを作っていざデプロイ。

そして、iPhoneなどの実機で確認。

しかし、開発時にレスポンシブ対応させたのにも関わらずレイアウトが異なってしまうってことに陥ってしまいます。

今回は、background-attachment: fixed;が効かないことについてまとめてみました。

background-attachment: fixed;が効かない問題

スクロール時に背景画像を固定したい時、background-attachment: fixed;を使用すれば背景画像の固定が出来ます。

しかし、これ。iOSでは思うように動作しません。

と、言うよりも

background-attachment: fixed;
background-size: cover

を同時に使用した場合に動きません。

なぜか?

iOS has an issue preventing background-attachment: fixed from being used with background-size: cover - see details

公式でも記載されているバグみたいです。

では、どうすれば?

擬似要素を活用する

iOSでも背景を固定するためには、

「bodyの擬似要素にbackground-imageをおく」
(ちなみに、全体を囲う要素であればbodyでなくてもかまいません。)

事で実現できます。

sample.css
body:before{
    content: "";
    display: block;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1;
    width: 100%;
    height: 100vh;
    background: url("#{$bgPath}about_back.jpeg") center no-repeat;
    background-size: cover;
}

要は、擬似要素ごと画面幅いっぱいに広げて固定します。

画像を固定するのではなく、要素を固定することになるため背景を固定できます。

そのため、
background-attachment: fixed;ではなく、position: fixed;を使用します。

height: 100vh;で画面の高さいっぱいにheightをとっています

【ポイント】

・背景画像の固定ではなく、要素自体の固定を利用することで、background-attachment: fixed;の利用を避ける。

参考

background:fixedでの背景固定はiOS(iPhone)でうまく動かないのでこれを使いましょう

【CSS】background-attachment:fixedがスマホだけ効かない原因と対処法

3
4
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
3
4