CSS: Why “vertical-align: middle” does not work?

2019-03-24 12:28发布

Consider the following example: (live demo here)

HTML:

<a><img src="http://img.brothersoft.com/icon/softimage/s/smiley.s_challenge-131939.jpeg" /></a>

CSS:

a {
    display: block;
    background: #000;
    line-height: 40px;  
}
img {
    vertical-align: middle;
}

The output is:

enter image description here

Why the image is not vertically centered ?

How could I fix that so it will work in all major browsers ?

Please don't assume any image size (like 32x32 in this case), because in the real case the image size is unknown.

8条回答
smile是对你的礼貌
2楼-- · 2019-03-24 13:18

I can't really tell you the specifics as to why this happens (I'm curious myself). But this works for me:

a {
    display: block;
    background: #000;
    line-height: 40px;  
}
img {
    vertical-align: middle;
    margin-top:-4px; /* this work for me with any given line-height or img height */
}
查看更多
Deceive 欺骗
3楼-- · 2019-03-24 13:19

You can use position:absolute; for this.

For example:

a {
    display: block;
    background: #000;
    line-height: 40px;
    height:80px;
    position:relative;  
}

img {
    position:absolute;
    top:50%;
    margin-top:-16px;
}

NOTE: This gives margin-top half of the image size.

Check this http://jsfiddle.net/cXUnT/7/

查看更多
登录 后发表回答