css - 为什么当我在一个行高为 div 的中心放置一个图像时,顶部会出现 3px 的间隙?

标签 css vertical-alignment gaps-in-visuals

看看this page .右边的图像应该在它们的 div 中居中。但如果你仔细观察,顶部有一个大约 3 像素的小边框。如果您禁用 overflow: hidden(通过 firebug 或 IE8 等效项),它会伸出底部。

HTML 是这样的:

<div class="small">
    <img src="/images/photos/Bedroom.jpg" alt="Bedroom" />
</div>
<div class="small">
    <img src="/images/photos/View.jpg" alt="View" />
</div>

还有 CSS,这个:

div.small
{
    width:100px;
    height:100px;
    line-height:100px;
    text-align:center;
    overflow:hidden;
    margin:5px;
    background-color: #C0C0C0;
    float:left;
}
div.small img
{
    vertical-align: middle;
    max-width:100px;
    max-height:100px;
    display: inline;
}

是什么造成了这个神秘的差距?我检查了边距和填充,它们似乎不是问题所在。

最佳答案

注意:我不完全确定这个解释是否正确,但对我来说似乎是合理的。

首先,让我们看看规范在 leading and half-leading 上是怎么说的:

Since the value of 'line-height' may be different from the height of the content area there may be space above and below rendered glyphs. The difference between the content height and the used value of 'line-height' is called the leading. Half the leading is called the half-leading.

User agents center glyphs vertically in an inline box, adding half-leading on the top and bottom. For example, if a piece of text is '12px' high and the 'line-height' value is '14px', 2pxs of extra space should be added: 1px above and 1px below the letters. (This applies to empty boxes as well, as if the empty box contained an infinitely narrow letter.)

到目前为止,还不错。因此,div.small 中任何高度小于 div.smallline-height 的行框都将垂直居中div.small。现在让我们看看the vertical-align property ,特别是 middle 值:

Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

注意这里不一定是line box的中心!确切的位置将随着您选择的字体和大小而改变。您可以通过放大和缩小文本来验证这一点:间隙的大小会发生变化。

如您所见,设置 font-size: 0 可以完全消除间隙。由于字体现在没有高度,行框的前导和半前导均为 50px,基线垂直居中。要呈现 vertical-align: middle 图像,浏览器将其中点设置为该基线,加上字体的 x 高度,现在为零。这给出了一个垂直居中的图像。

关于css - 为什么当我在一个行高为 div 的中心放置一个图像时,顶部会出现 3px 的间隙?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1368253/

相关文章:

php - 在 tinymce 中使用 div 标签作为默认而不是段落

javascript - element.style.display = 'none' 在 firefox 中不起作用,但在 chrome 中有效

html - 如何覆盖CSS背景?

Java Gui,隐藏其中一些元素后元素之间的间隙

wpf - WPF选项卡标题之间的间距

html - 设置标题 anchor 时如何防止标题标签继承超链接样式

html - 如何让元素的底部在 HTML/CSS 中匹配

html - 如何在 CSS 中将标签与 div 的 "BOTTOM"对齐?

html - 为什么我的 h 标签不能垂直对齐?