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;
}
I have found a great solution for fixed backgrounds on mobile devices requiring no JavaScript at all.
Please be aware of the negative
z-index
value of-10
.html
root element defaultz-index
is0
. This value must be the smallestz-index
to have it as background.I think that mobile devices dont work with fixed positions. You should try with some js plugin like skrollr.js (for example). With this kind of plugin you can select the position of your div (or whatever) in function of scrollbar position.
I'm late to the party, but this is (unbelievably) still a problem as of the 11.05.2017. Here is a simple solution which will also work cross-platform with linear gradients:
I've been having the same problem, but now it works. All I had to do was add
background-size: cover !important;
and it works on my Android device!The entire code looks like this:
Thanks a lot @taylan derinbay and @Vincent!
"background-size: cover;" causes a lot of issues on all mobile browsers except Firefox!
This fixed my issue:
Found a perfect solution for the problem 100% working on mobile as well as desktop
https://codepen.io/mrinaljain/pen/YObgEP