Here is my example
HTML:
<div class="container">
<img src="http://placehold.it/500x500" alt="500x500" />
</div>
<div class="container">
<img src="http://placehold.it/100x500" alt="100x500" />
</div>
<div class="container">
<img src="http://placehold.it/500x100" alt="500x100" />
</div>
<div class="container">
<img src="http://placehold.it/500x800" alt="500x800" />
</div>
<div class="container">
<img src="http://placehold.it/800x500" alt="800x500" />
</div>
<div class="container">
<img src="http://placehold.it/100x100" alt="100x100" />
</div>
<div class="container">
<img src="http://placehold.it/200x100" alt="200x100" />
</div>
CSS:
div.container { width: 200px; height: 200px; line-height: 200px; overflow: hidden; border: 10px solid white; box-shadow: 0 1px 8px #BBB; margin: 10px; text-align: center; }
div.container img { position: relative; vertical-align:middle; }
div.container img.wide { max-height: 100%; }
div.container img.tall { max-width: 100%; }
div.container img.square { max-width: 100%; }
Javascript:
$(window).load( function(){
var $imgs = $("div.container img");
$imgs.each( function(){
var cW = $(this).parent().width();
var cH = $(this).parent().height();
var w = $(this).width(); //I want the CURRENT width, not original!!
var h = $(this).height(); //I want the CURRENT height, not original!!
var dW = w - cW;
var dH = h - cH;
console.log( cW + " " + cH + " " + w + " " + h + " " + dW + " " + dH );
if ( w > h ){
$(this).addClass("wide");
$(this).css("left", -dW/2);
}
else if ( w < h ){
$(this).addClass("tall");
$(this).css("top", -dH/2);
}
else { $(this).addClass("square"); }
});
});
I’m adding, via javascript, a class to the image elements based on their proportions. The 3 classes will set the max-width and max-height css properties for the images, thus resizing them.
After that, I need the resized image’s dimensions, but all I can get is the original image’s dimensions. That’s no good! I tried using width(), outerWidth, naturalWidth, every kind of width, but I just can’t get it right.
So, is there a way to get the image’s dimensions after CSS rules like max-width and max-height have been applied to it? Preferably a consistent way, not using timers and intervals, or stuff like that.
Thanks a lot!
Check out this jsfiddle. You are trying to get widht/height BEFORE you apply a class with
max-height/max-widthinstead of after it is applied.Here is test code (check second console.log):
width(),outerWidth– this always return current width.naturalWidth/naturalHeight– this is to get an original,like with no any styles applied, width/height of image (available for IMG tag only in newer browsers)