Search code examples
javascriptjqueryhtmlcssshrinkwrap

Make wrapper div shrink around dynamic, responsive image


After countless look-ups, I still can't get an definitive answer.

I need a div to wrap around a responsive image, but the image

  • is of unkwown dimensions
  • should have a height of 70% of wrapper, but the width can be anything, according to dimension ratio.
  • should keep dimension ratio when window sized up and down (at the moment only keeps dimension ratio when scaling up)

JSFiddle: http://jsfiddle.net/8c15uw1d/

div {
height: 60%;
display: inline-block;
border: 2px solid brown;
}
img {
height: 70%;
width:auto:
display: block;
}

Strangely in IE9 this works as required, but in Chrome the image scales up over the div, doesn't 'take it along'.

  1. How do I achieve this? I strongly suspect it could only be done with JS.

  2. If I indeed need to do this in Jquery (on browser resize) - say I have 100 of these images of 400px x 200px on the page, will site performance be significantly impaired each time the window is resized? Is this considered bad practise?


Solution

  • This is what I came up with:

    $(window).resize(function () {
        $("div").css("width", ($("img").width() / $(window).width()) * 100 + "%");
    });
    

    Since CSS wasn't working perfectly for me, I used JQuery to cater for the width change.

    Here is the JSFiddle demo

    Basically the CSS already lets the image resize as per ration. The JQuery code gets the percentage width of the img tag and sets it as the div width in percentage, causing the container to always wrap around the image when the window is resized.