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; }
background-attachment: fixed in CSS, at best, does not work well in mobile browsers, and at worst is not even supported by the most widely used mobile browsers. You can ditch this idea completely and let the background scroll on small screens using media queries. Or get around it with a small fix.
To make a background image not repeat in HTML, specify no-repeat in the background-repeat property or the background shorthand property. The background image is set to 'no-repeat' using the 'background-repeat' property.
To keep your background fixed, scroll, or local in CSS, we have to use the background-attachment property. Background-attachment: This property is used in CSS to set a background image as fixed or scroll. The default value of this property is scroll.
I have found a great solution for fixed backgrounds on mobile devices requiring no JavaScript at all.
body:before { content: ""; display: block; position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: -10; background: url(photos/2452.jpg) no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }
Please be aware of the negative z-index
value of -10
. html
root element default z-index
is 0
. This value must be the smallest z-index
to have it as background.
I had a very simple solution for this, after struggling with all the methods of fixing this.
i had the problem on my mobile IOS devices.
css (desktop)
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap { background-size: auto; background-attachment: fixed; } .widget-wrap { background-attachment: scroll; }
Then i overwrite it with media query removing "fixed" as background attachment.
css (mobile)
@media (max-width: 767px) { #ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap { background-attachment: initial; } }
initial - Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.
This worked for me on every device. Hope it helps someone else as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With