center image in div
by ddehghan
HTML
<div class='container'>
<img class="test1" src='http://fakeimg.pl/100x250/' />
</div>
<br>
<div class='container'>
<img class="test2" src='http://fakeimg.pl/100x250/' />
</div>
<br>
<div class='container'>
<img class="test1" src='http://fakeimg.pl/250x50/' />
</div>
<br>
<div class='container'>
<img class="test2" src='http://fakeimg.pl/250x50/' />
</div>
<br>
<div class='container'>
<img class="test1" src='http://fakeimg.pl/400x500/' />
</div>
<br>
<div class='container'>
<img class="test2" src='http://fakeimg.pl/400x500/' />
</div>
<br>
<div class='container'>
<img class="test1" src='http://fakeimg.pl/25x50/' />
</div>
<br>
<div class='container'>
<img class="test2" src='http://fakeimg.pl/25x50/' />
</div>
<br>
<div class='container'>
<img class="test1" src='http://fakeimg.pl/500x100/' />
</div>
<br>
<div class='container'>
<img class="test2" src='http://fakeimg.pl/500x100/' />
</div>
CSS
.container {
width: 300px;
height: 200px;
border: 1px solid green;
}
.test1 {
max-width: 100%;
max-height: 100%;
}
.test2 {
display: block;
}
JavaScript
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return {width: srcWidth * ratio, height: srcHeight * ratio};
}
$(".test2").one("load", function () {
var $img = $(this);
var pw = this.parentNode.clientWidth;
var ph = this.parentNode.clientHeight;
var x = calculateAspectRatioFit(this.width, this.height, pw, ph);
console.log(x);
//debugger;
if (x.width > x.height) {
$img.css({
'width': '100%',
'height': 'auto',
'margin-top': Math.abs(ph - x.height) / 2.0
});
console.log({
pw: pw,
ph: ph,
w: this.width,
h: this.height,
m: Math.abs(ph - this.height) / 2.0
});
} else {
$img.css({
'width': 'auto',
'height': '100%',
'margin-left': Math.abs(pw - x.width) / 2.0
});
console.log({
pw: pw,
ph: ph,
w: this.width,
h: this.height,
m: Math.abs(pw - this.width) / 2.0
});
}
}).each(function () {
if (this.complete) $(this).load();
});