LoginSignup
1
1

More than 3 years have passed since last update.

モバイル画面でbackground-attachement: fixed; が効かない

Posted at

モバイル画面でbackground-attachement: fixed; が効かない場合

ちょっとおしゃれなホームページを作ろうと思ったら、
簡単にできるものとして背景固定のパララックス風のページデザインがありますよね。

こんな感じのウェブサイト

その際は

hogehoge.css
body{
   background-image: url('hogehoge.jpg');
   background-attachment: fixed;
   background-size: cover;
}

とかで背景画像を固定するのが一般的かな?

が、実はこの
background-attachment: fixed;
iOSではうまく動かないんです。

正しくは、iOSモバイル画面で見てみると背景画面が固定されません、、、
background-attachment:fixed;とbackground-sizeはモバイルだと衝突するみたいです。

じゃあどうするの?ってことで
以下解決策

bodyに::before疑似要素で背景画像を指定!!

hogehoge.css
body{
   width:100%;
   z-index: 0;
}

body::before{
   content: "";
   display: block;
   position: fixed;
   top: 0;
   left: 0;
   z-index: -1;
   width: 100%;
   height: 100vh;
   background-image: url('hogehoge.jpg');
   background-size: cover;
}

bodyの擬似要素(z-index:-1;)をbody(z-index:0;)の一枚裏におけばおk

content: "";

 
→ 私のような初学者は『これ何?』とお思いだろうが、
::after とか ::before についてはcontentプロパティがないと要素として全く見えなくなります。
のでつけときましょう。

これで::beforeを使ったbackground-attachment: fixed;の画面を実装することができました。

モバイルでの背景固定パララックス風デザインを実装する際は是非ご参考に!

1
1
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
1
1