greener greener - 13 days ago 5
CSS Question

How to use CSS media query to scale background-image to viewing window

I have this large image as a background for a website:

body {
background: #000 url(/assets/img/living.jpg) no-repeat center center;
background-attachment: fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height:100%;
}


But on my mobile device (iPhone 4S - Safari), the
background-attachment: fixed
does't seem to be having the same effect as it would on a desktop. Why is that and can I use a media query to fix that?

Answer

Try this - you shouldn't need height:100% or even necessarily need a media query to handle the background image. The CSS3 background-size:cover property handles that pretty well on its own. Works well for me on all mobile devices I've tested - especially well on Android, mobile version browsers and all tablets.

body {
    background-color: #000; 
    background-image: url(/assets/img/living.jpg); 
    background-repeat: no-repeat; 
    background-position: center;
    background-attachment: fixed;       
    webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
}