Css – Background image fixed and cover on mobile / tablet

cssresponsive-designsmartphonetablet

How do you get a fixed background image that scales to viewport to work correctly on smartphone / tablet?

Any of the methods mentioned here do not work well with what I've tested (Galaxy Nexus & TF300t, using default browser, Firefox, or Chrome all have trouble with flashing / strange resizing, or ignoring the "cover" instruction)

The one thing I've come to see is to not put the background image on the HTML tag for touch devices, because they seems to scroll a full height viewport rather than scroll within the HTML tag.

body {
  background: black url("../img/cover.jpg") no-repeat top center fixed;
  -webkit-background-size: cover; 
  -moz-background-size: cover; 
  -o-background-size: cover; 
  background-size: cover;
}

Best Answer

I've written some months ago an approach what fits your needs: http://plugins.jquery.com/fitpic/

HTML

<img src="http://ge.tt/api/1/files/1jN8IzR/0/blob?download" class='bg'>

CSS not really needed

.bg {
    position: fixed;
    top: 0;
    left: 0;
    z-index: -1
}

JS

var fitPic = (function() {
    var winW = $(window).width(),
        winH = window.innerHeight || $(window).height(); // `innerHeight` for mobile safari

    $(".bg").each(function() {

        var elem = $(this),
            elemW = elem.width(),
            elemH = elem.height(),

            imgW = (elemW * winH) / elemH,
            imgH = (elemH * winW) / elemW,

            newW = imgH < winH ? imgW : winW,
            newH = imgH < winH ? winH : imgH;

        this.style.width = newW + "px";
        this.style.height = newH + "px";

    });
});

$(window).on('load resize', fitPic);