fixed background for part of a site (div) in iOS

2019-03-01 10:30发布

I want to have a fixed position background image that covers the whole screen only for a section of my website (actually two sections, but independently, so there is no difference). I use this CSS on the container DIV of the section:

#wrapper {
  background-image: url(../img/bg1_IMG_1509.jpg);
  background-position: center center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;    
}

(Note: I used the seperate properties instead of the shorthand background hoping that this would be compatible with more devices and browsers, but it doesn's seem to be like that.)

This works more or less well in all desktop and browsers and also in some browsers on android, but not at all in iOS. In iOS, the background is not only being scrolled, but also extremely stretched vertically so that the height of the background image covers the whole DIV, which has a lot of content and becomes quite high on a mobile device, which leads to seeing more or less single pixel blown up on the screen. So, neither fixed nor cover work.

I am aware / have read answers about fixed position workarounds for iOS that used a DIV inside the <body> tag which got position: fixed and a full-screen background image. But I don't want this on the whole body, but only in two (independent) sections, and in this situation that workaround can't be used.

1条回答
beautiful°
2楼-- · 2019-03-01 11:16

I found this :

.bg {
    background: url(image.jpg);
    background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    height: 100%;
    width: 100%;
    position: fixed;
    background-position: center center;
    background-repeat: no-repeat;
}

here : https://css-tricks.com/forums/topic/full-page-backgrounds-on-ios-background-size-cover/page/3/

basically you put your background in another div and give the fixed attribute to the div instead of the background. You need to add z-index:-1; and add white background or whatever to hide the picture where you don't want to see it.

查看更多
登录 后发表回答