问题
I have an HTML/CSS webpage with a background image. The image is fixed on desktop and looks great, and the main text scrolls over it as intended.
On iPhone6, however, it looks horrible: sometimes, two versions of the photo show up; both versions scroll with the image, rather than staying put, and the second one is stretched to the entire length of the page.
I have searched high and low on stack overflow for answers, and none of the answers work: media queries don't appear to work; -webkit doesn't appear to work; nothing seems to work.
It's 2017, so maybe it's time for an updated answer: how to avoid this problem on iPhone6 mobile (and safari and mobile safari in general)?
This is the code I have so far:
body {
background-image: url(rsz_background.jpg);
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
}
NOTE: here is a live link to the website: www.successfulnewyear.com If you view the site using chrome dev tools for iphone6, or iphone5--it looks as if it scrolls beautifully with the background staying put. However, if you actually visit the site on your iphone5 or iphone6, you will see that the photo enlarges to the entire size of the website, and it scrolls instead of staying fixed.
回答1:
You can put the background-image in another div just below the body. Make this div position: fixed. Then put the background image on this without any 'fixed' parameter.
<html lang="en">
<head></head>
<body>
<div class="bkgdImage"></div>
<header></header>
<section id="homeContainer">
//content etc
</section>
</body>
</html>
CSS:
html{
height: 100%;
min-height: 100%;
}
body {
min-height: 100%;
width: 100%;
height: 100%;
margin: 0;
}
.bkgdImage {
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100; (so it's behind your content)
margin: 0;
background: url(../yourimage.jpg) center center no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
This works on my iPhone 5 and all mobile browers I've tested on. You might need to change the heights of html & body to suit your needs. You can see it working here and did a blog post on it.
来源:https://stackoverflow.com/questions/41691599/2017-answer-to-how-to-make-background-image-fixed-on-iphone6