问题
I use following code to center images horizontally and vertically in DIV
Properties given to DIV is width
& height
, overflow:hidden
, and display:block
.
Problem: margin-top
and margin-left
miscalculated only in Chrome, while code is working perfectly in FF and IE
$('.centerImage').each(function(i) {
var divH = $(this).parent().height();
var divW = $(this).parent().width();
var orgImgH = $(this).height();
var orgImgW = $(this).width();
if (orgImgH > orgImgW) {
$(this).css('width', divW);
var imgH = $(this).height();
var mTop = (divH - imgH) / 2;
$(this).css("margin-top", (mTop < 0) ? mTop : -mTop); //if margin-top value is less than 0 use as is and greater than 0 multiply by -1
} else {
$(this).css('height', divH);
var imgW = $(this).width();
var mLeft = (divW - imgW) / 2;
//alert(imgW); alert(mLeft); //chrome bug
$(this).css("margin-left", (mLeft < 0) ? mLeft : -mLeft);
}
});
Any ideas?
来源:https://stackoverflow.com/questions/12468124/why-are-img-and-div-widths-miscalculated-in-chrome