Images centered vertically with line-height have center miscalculated by 2 pixels
Looks like a bug in various browsers.
by keaukraine
HTML
<div class="img-wrapper-center" id="div1">
<!-- 80x80 -->
<img src="http://gravatar.com/avatar" id="img1"/>
</div>
<div class="img-wrapper-center" id="div2">
<!-- 495x370 -->
<img src="http://www.w3.org/html/logo/img/class-header-semantics.jpg" id="img2" />
</div>
<p>
Note how the second image is misaligned down by two pixels.
The first one is mis-aligned the same way. Sizes and coordinates are below.
<br/>
</p>
<p id='debugger'>debug info goes here</p>
CSS
* { margin: 0; padding: 0; border: 0px solid cyan; } /* reset all margins, paddings and borders */
html {
font-size: 16px;
line-height: normal;
}
body {
line-height: 100%;
background: gray;
}
/* works for images smaller or larger than the wrapper */
.img-wrapper-center {
width: 400px;
height: 200px; /* necessary, besides line-height, if images are taller than it */
line-height: 200px; /* must be equal to line-height */
text-align: center;
background: white;
}
.img-wrapper-center img {
vertical-align: middle;
/* Comment the two rules below. The first image will still be mis-aligned by two pixels, but the second will not. */
max-width: 100%; max-height: 100%; /* force scaling down large images */
}
.img-wrapper-center:nth-child(2n) {
background: green;
}
.img-wrapper-center
{
font-size:0;
}
JavaScript
setTimeout(display_numbers, 100);
function display_numbers() {
var coordinates = 'div1 top: ' + document.getElementById('div1').offsetTop + '<br/>'
+ ('image 1 height: ' + document.getElementById('img1').offsetHeight + '<br/>')
+ ('div1 height: ' + (document.getElementById('div1').offsetHeight) + '<br/>')
+ ('image 1 top should be at: ' + (document.getElementById('div1').offsetHeight - document.getElementById('img1').height) / 2 + '<br/>')
+ ('image 1 top actually is at: ' + document.getElementById('img1').offsetTop + '<br/>')
+ ('div2 top: ' + document.getElementById('div2').offsetTop + '<br/>')
+ ('img2 top: ' + document.getElementById('img2').offsetTop + '<br/>')
document.getElementById('debugger').innerHTML = coordinates;
}