I had a problem with one of my current projects where I was supposed to have an image enclosed in a div with fixed dimensions.
2 | < img src = "someimage.jpg" , :id = "resize-div" > |
For the dimensions of the div, you can set it inline or use css file:
Now since not all images will fit this aspect ratio you’ll encounter problems easily enough. With images smaller than the div, I had little problem letting the css to handle it so it’s situated perfectly center in the div. I didn’t include it here to shorten the codes i need to display :).
Judging from the code shown above, you’ll not that if you have larger images that exceeded the div’s set height and width (especially those width different aspect ratios), a pure css solution simply won’t work (or at least I couldn’t make it work…. :/) so I thought of using JQuery to work it out for me.
Here’s my script to autofit images in a div using JQuery.
2 | var divElem = $( "#resize-div" ); |
3 | var maxht = divElem.height(); |
4 | var maxwdt = divElem.width(); |
5 | var imgElem = $( "#resize-image" ); |
6 | var ht = imgElem.height(); |
7 | var wdt = imgElem.width(); |
10 | $( "#resize-image" ).css({ 'height' : "auto" , 'width' : maxwdt}); |
12 | $( "#resize-image" ).css({ 'height' : "auto" , 'width' : wdt}); |
16 | $( "#resize-image" ).css({ 'height' : maxht, 'width' : "auto" }); |
18 | $( "#resize-image" ).css({ 'height' : ht, 'width' : "auto" }); |