简体   繁体   中英

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?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM