*完美*垂直图像对齐 [英] *Perfect* vertical image alignment
问题描述
我有固定大小的方形格并希望里面放置一个任意大小的图像,使其居中水平和垂直方向,使用CSS。水平很简单:
I have a square div of fixed size and wish to place an arbitrary size image inside so that it is centred both horizontally and vertically, using CSS. Horizontally is easy:
.container { text-align: center }
有关的垂直,常见的解决方案是:
For the vertical, the common solution is:
.container {
height: 50px;
line-height: 50px;
}
img {
vertical-align: middle;
}
但是,这是不完美,根据不同的字体大小,图像将围绕2-4px太远了。
But this is not perfect, depending on the font size, the image will be around 2-4px too far down.
要我理解,这是因为,中间用于垂直对齐是不是真正的中间,但是这是接近中间上的字体的特定位置。 (稍微哈克)解决方法是:
To my understanding, this is because the "middle" used for vertical-align is not really the middle, but a particular position on the font that is close to the middle. A (slightly hacky) workaround would be:
container {
font-size: 0;
}
和这部作品在Chrome和IE7,但不是IE8。我们希望能够让所有字体线条的相同点,在中间,但它似乎是打了小姐取决于浏览器,很可能使用的字体。
and this works in Chrome and IE7, but not IE8. We are hoping to make all font lines the same point, in the middle, but it seems to be hit-and-miss depending on the browser and, probably, the font used.
唯一的解决办法我能想到的是破解行高,使得它略短,使图像出现在正确的位置,但似乎极为脆弱。有没有更好的解决办法?
The only solution I can think of is to hack the line-height, making it slightly shorter, to make the image appear in the right location, but it seems extremely fragile. Is there a better solution?
在这里看到所有三种解决方案的演示: http://jsfiddle.net/usvrj/3/
See a demo of all three solutions here: http://jsfiddle.net/usvrj/3/
那些没有IE8可能会发现这个截图有用的:
Those without IE8 may find this screenshot useful:
推荐答案
如何使用您的图片作为背景?这样,您就可以集中它始终无处不在。这些方针的东西:
How about using your image as a background? This way you could center it consistently everywhere. Something along these lines:
margin:5px;
padding:0;
background:url(http://dummyimage.com/50) no-repeat center center red;
height:60px;
width:60px;
这篇关于*完美*垂直图像对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!