center image vertically and horizontally with query
by KURO KUMO
HTML
<div class="block-wrap">
<div class="img-block-center">
<img src="http://placehold.it/200x200/">
</div>
</div>
<div class="block-wrap">
<div class="img-block-center">
<img src="http://placehold.it/800x230/">
</div>
</div>
<div class="block-wrap">
<div class="img-block-center">
<img src="http://placehold.it/100x300/">
</div>
</div>
CSS
.block-wrap{
width: 50%;
display: block;
margin: 1.5%;
float:left;
}
.img-block-center {
width: 100%;
background: #eee;
display: block;
}
.log {
margin: 1.5%;
margin: 1.5%;
font-size:40px
}
JavaScript
resizeimages();
$( window ).resize(function() {
$( ".resizelog" ).text( "resized!" );
resizeimages();
});
function resizeimages(){
$(".img-block-center").each(function(index) {
var img = $(this).find("img");
var blockW = $(this).parent().width();
var imgW = img.width();
var imgH = img.height();
var imgR = imgW / imgH;
$(this).width(blockW).height(blockW);
//square
if (imgR == 1) {
img.width(blockW).height(blockW);
}
//portrait
if (imgR < 1) {
img.height(blockW);
var resizeW = img.width();
var resizeH = img.height();
var marge = resizeH - resizeW;
img.css({
"margin-left": marge / 2,
"margin-right": marge / 2
});
};
//landscape
if (imgR > 1) {
img.width(blockW);
var resizeW = img.width();
var resizeH = img.height();
var marge = resizeW - resizeH;
img.css({
"margin-top": marge / 2,
"margin-bottom": marge / 2
});
};
});
}