Search code examples
javascriptjquerymathbackground-size

How to emulate background-size: cover on <img>?


How can I resize and reposition the image inside a box, in such way that it covers the entire box, similar to how background-size: cover works.

<div class="box" style="width: 100px; height: 100px;">
  <img src="pic.jpg" width="413" height="325">
</div>

I know I have to add overflow:hidden to the box and the image needs position: absolute. But what's the formula that gets me the right new size for the image, and left + top positions?


Solution

  • this may be easier

    jQuery

    $('.box').each(function() {
        //set size
        var th = $(this).height(),//box height
            tw = $(this).width(),//box width
            im = $(this).children('img'),//image
            ih = im.height(),//inital image height
            iw = im.width();//initial image width
        if (ih>iw) {//if portrait
            im.addClass('ww').removeClass('wh');//set width 100%
        } else {//if landscape
            im.addClass('wh').removeClass('ww');//set height 100%
        }
        //set offset
        var nh = im.height(),//new image height
            nw = im.width(),//new image width
            hd = (nh-th)/2,//half dif img/box height
            wd = (nw-tw)/2;//half dif img/box width
        if (nh<nw) {//if portrait
            im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
        } else {//if landscape
            im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
        }
    });
    

    css

    .box{height:100px;width:100px;overflow:hidden}
    .wh{height:100%!important}
    .ww{width:100%!important}
    

    This should handle any size/orientation, and will not only resize, but offset the images. All without relative or absolute positioning.

    made a fiddle: http://jsfiddle.net/filever10/W8aLN/