CSS background-size: cover replacement for Mobile Safari

Josh picture Josh · Aug 25, 2013 · Viewed 162.4k times · Source

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:

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?

Answer

mkubilayk picture mkubilayk · Jan 30, 2014

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.