短篇故事:
jsfiddle在这里 http://jsfiddle.net/dandv/keucK/。这种行为在 Chrome 21、Firefox 15 和 IE9 中始终是错误的,这让我觉得我误解了 CSS 规范。
更长的故事:
我想使用行高将图像垂直居中。我已将图像容器的高度设置为等于行高,并重置了所有元素的边距、填充和边框,但图像比应有的位置低了 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>
你必须设置零font-size
用于容器div
元素。
由于图像显示为内联元素,因此它们会受到容器中文本的影响div
. Zero font-size
解决这个问题:
.img-wrapper-center
{
font-size:0;
}
这是小提琴:http://jsfiddle.net/bZBsR/ http://jsfiddle.net/bZBsR/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)