短篇故事:
这里的jsfiddle 。 该行为是在Chrome 21,Firefox的15和IE9,这让我觉得我误解一些关于CSS规范一致的错误。
更长的故事:
我想垂直居中的图像使用的line-height。 我已经设置图像容器等于行高的高度,我已经复位利润率,填充和边框所有元素,但是该图像是低于它应该是2个像素。 这种情况发生在图像是否是比容器更小,或比它更大(在这种情况下,我使用的max-width: 100; max-height: 100%
至大小下来)。
图像有偶数个在这两种情况下的像素。 我不会想那么多为比容器更小的图像,但是对于较大的图像,从容器背景2像素线将在图像的顶部流血通过。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Images centered vertically with line-height have center miscalculated by 2 pixels</title>
<style type="text/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;
}
.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 */
}
</style>
</head>
<body>
<div class="img-wrapper-center" id="div1">
<img src="http://gravatar.com/avatar" id="img1"/> <!-- 80x80 -->
</div>
<div class="img-wrapper-center" id="div2" style="background: green">
<img src="http://www.w3.org/html/logo/img/class-header-semantics.jpg" id="img2" /> <!-- 495x370 -->
</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.
</p>
<script>
document.writeln('div1 top: ' + document.getElementById('div1').offsetTop + '<br/>');
document.writeln('image 1 height: ' + document.getElementById('img1').offsetHeight + '<br/>');
document.writeln('div1 height: ' + (document.getElementById('div1').offsetHeight) + '<br/>');
document.writeln('image 1 top should be at: ' + (document.getElementById('div1').offsetHeight - document.getElementById('img1').height) / 2 + '<br/>');
document.writeln('image 1 top actually is at: ' + document.getElementById('img1').offsetTop + '<br/>');
document.writeln('div2 top: ' + document.getElementById('div2').offsetTop + '<br/>');
document.writeln('img2 top: ' + document.getElementById('img2').offsetTop + '<br/>');
</script>
</body>
</html>