petestar
petestar

Reputation: 57

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

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?

Upvotes: 0

Views: 1295

Answers (2)

Martin Verner
Martin Verner

Reputation: 742

I'm not sure if you want the div to shrink in width, but here css for having the ratio kept. I believe this will scale well on a computer, perhaps not on a mobile device (for 100s of images). Perhaps consider making it fetch more when scroll reach bottom (like google images search).

html, body {
height: 100%;
width: 100%;
}

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

img {
max-height: 70%;
max-width: 100%;
width:auto:
display: block;
}

Upvotes: 1

Ahs N
Ahs N

Reputation: 8386

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.

Upvotes: 2

Related Questions