Html – CSS background-size: cover replacement for Mobile Safari

csshtmlmobile-safari

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?

Best Answer

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.