开发者

Vertical centering an inline image in a single-line containing box

Example: http://jsfiddle.net/Kgn5R/

I'm trying to figure out why the inline image doesn't wind up the vertical center of the container.

<div class="container">
    <img src="http://dummyimage.com/46x46/000/fff.png" />
</div>

CSS:

.container {
    height: 50px;
    width: 80px;
    line-height: 50px;
    background-color: gra开发者_运维问答y;
    text-align: center;
}

img {
    display: inline;
    vertical-align: middle;
}

Any help or even alternative solutions are much appreciated. If you'd like me to elaborate on something, I'd be happy to.


Try setting the font-size of the container to for example 0.

According to W3:

Vertical-align: middle; Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

So this has something to do with the height of the letter 'x' of the parent, which is 0 if you set the font size to 0:

.container {
    font-size: 0;
    height: 50px;
    width: 80px;
    line-height: 50px;
    background-color: gray;
    text-align: center;
}

img {
    display: inline;
    vertical-align: middle;
}

This seems to work reliable


Horrific I know, but I've spent so much time trying to get something to be aligned vertically in the middle that I gave up and wrapped it in a table.

An alternative would be to use JavaScript to get the parent height and the element height, and work out the padding to make it precisely in the middle.

The best method is to have a design which does not require such pixel precision, but unfortunately it's not always my choice.

In your case here, adding font-size: 0 to the container should work.


Using text attributes to center images or other elements can be painful. If you know the size of your image, do it with absolute positioning:

.container {
    position: relative;
    height: 50px;
    width: 80px;
    background-color: gray;
    text-align: center;
}

img {
    position: absolute;
    top: 50%;
    margin-top: -23px;
    left: 50%;
    margin-left: -23px;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜