Hi I have several divs on my page which have background images that I want to expand to cover the entire div which in turn can expand to fill the width of the viewport.
Obviously background-size: cover
behaves unexpectedly on iOS devices. I've seen some examples of how to fix it, but I can't make them work in my situation. Ideally I'd prefer not to add extra <img>
tags to the HTML but if it's the only way then I will.
Here is my code:
.section { margin: 0 auto; position: relative; padding: 0 0 320px 0; width: 100%; } #section1 { background: url(...) 50% 0 no-repeat fixed; background-size: cover; } #section2 { background: url(...) 50% 0 no-repeat fixed; background-size: cover; } #section3 { background: url(...) 50% 0 no-repeat fixed; background-size: cover; }
<body> <div id="section1" class="section"> ... </div> <div id="section2" class="section"> ... </div> <div id="section3" class="section"> ... </div> </body>
The question is, how can I get the background image to completely cover the section div, taking into account the variable width of the browser and the variable height of the content in the div?
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.
cover tells the browser to make sure the image always covers the entire container, even if it has to stretch the image or cut a little bit off one of the edges. contain , on the other hand, says to always show the whole image, even if that leaves a little space to the sides or bottom.
background-size:cover; means the background image will always fit the whole div , you won't be left with any empty spots in your div background-size:100% 100% won't leave any empty space too, but of course this will detroy the original image aspect ratio.
I have had a similar issue recently and realised that it's not due to background-size:cover
but background-attachment:fixed
.
I solved the issue by using a media query for iPhone and setting background-attachment
property to scroll
.
For my case:
.cover { background-size: cover; background-attachment: fixed; background-position: center center; @media (max-width: @iphone-screen) { background-attachment: scroll; } }
Edit: The code block is in LESS and assumes a pre-defined variable for @iphone-screen
. Thanks for the notice @stephband.
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