background: fixed no repeat not working on mobile

2019-01-04 00:08发布

I am building a webpage where I want the background image to scale to fit the whole screen, maintain aspect ratio and be fixed (so if you scroll down, the background image stays in the same place).

I have achieved this in desktop browsers with the CSS below, but it doesn't work on an iPhone or iPad. On those devices the background is too big (it continues below the fold) and if you scroll down far enough, the image will start repeating. Anyone have a fix? THanks!

HTML {
  background: url(photos/2452.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

14条回答
不美不萌又怎样
2楼-- · 2019-01-04 00:41

This is what i do and it works everythere :)

.container {
  background: url(${myImage})
  background-attachment: fixed;
  background-size: cover;
 transform: scale(1.1, 1.1);

}

then...

@media only screen and (max-width: 768px){
   background-size: 100% 100vh;
}
查看更多
Anthone
3楼-- · 2019-01-04 00:45

I have been busy using different posts and methods for two days trying to figure it out. I urge anyone to START by looking at the post by Eggs, and mess around with the codepen he and others have built.

This has been the only solution to work properly for me that I have found. I recommend his answer as a solution/ a good starting point at minimum for those of us still figuring out this problem in our own web applications.

I haven't gotten enough reputation yet to comment on his post, otherwise I would. I can't even vote on it yet or I would do that too.

This is the actual code I used:

html::before {
    content: ' ';
    display: block;
    background-image: url('path-to-your-image');
    background-position: bottom left; 
    /*For my instance this is how I have built my bg image. Indexes off the 
bottom left for consistency*/
    background-size: cover;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    position: fixed;
    z-index: -10; 
    /*I haven't tested my full app functionality after changing the z-index, but everything appears to work flawlessly right now.*/
}

I tried everything with his original code. When I had

background-position: center; 

chrome (on latest android update as of 1/8/18) would lag with updating the image's position, so when scrolling through the website there would be a patch of color where my navbar/URL bar of the browser was. Then it would disappear after the browser recalculated the image center(is what I assume was happening).

So, I recommend making an image around your footer or header like I did, and setting either top left/right or bottom left/right for your position.

In summary, THIS WORKS for me. So try it out if you're reading down this far and nothing has worked yet. Though you should've already hit the original post by now.

Thank you Eggs, and the other fellows you collaborated with on your Codepen.

查看更多
登录 后发表回答