Josh Josh - 7 months ago 87
HTML Question

CSS background-size: cover replacement for Mobile 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 HTML:

<body>
<div id="section1" class="section">
...
</div>
<div id="section2" class="section">
...
</div>
<div id="section3" class="section">
...
</div>
</body>


And the CSS:

.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;
}


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

I've had this issue on a lot of mobile views I've recently built.

My solution is still a pure CSS Fallback

http://css-tricks.com/perfect-full-page-background-image/ as three great methods, the latter two are fall backs for when CSS3's cover doesn't work.

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspet ratio */
  min-width: 100%;
  min-height: 100%;
}