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条回答
孤傲高冷的网名
2楼-- · 2019-03-24 12:56

If you know the vertical size of the element and the line height, then you can vertically center it by using vertical-align: top plus a top margin.

For illustration, I created: http://jsfiddle.net/feklee/cXUnT/30/

查看更多
Luminary・发光体
3楼-- · 2019-03-24 12:57

Not sure what's the cause.

Removing the line-height and adding margins to the image does the trick.

a {
  display: block;
  background: #f00;
}
img {
  margin: .3em auto;
  vertical-align: middle;
}
<a>
 <img src="https://placeimg.com/30/30/any">
</a>

查看更多
不美不萌又怎样
4楼-- · 2019-03-24 13:01

I had the same problem. This works for me:

 <style type="text/css">
    div.parent {
         position: relative;
    }

    /*vertical middle and horizontal center align*/
    img.child {
        bottom: 0;
        left: 0;
        margin: auto;
        position: absolute;
        right: 0;
        top: 0;
    }
    </style>

    <div class="parent">
        <img class="child"> 
    </div>
查看更多
疯言疯语
5楼-- · 2019-03-24 13:01

Just put the img tag inside a div tag the set display:table-cell vertical-align: middle to the div. Parent tag should be display:table

Example:

Css

a {
 display: table;
 background: #000;
 height:200px;
}
div {
 display:table-cell;
 vertical-align: middle;
}

HTML

<a>
 <div>
  <img src="http://img.brothersoft.com/icon/softimage/s/smiley.s_challenge-  131939.jpeg" />
 </div>
</a>
查看更多
6楼-- · 2019-03-24 13:03

You should have display: table-cell I think, this works only in tables.. I use line-height equal to height of the element and it works too.

查看更多
Juvenile、少年°
7楼-- · 2019-03-24 13:06

Try using a background image on an <a>:

<a href="#"></a>    
a {display:block;background:#000;line-height:40px;background:#000 url(http://img.brothersoft.com/icon/softimage/s/smiley.s_challenge-131939.jpeg) no-repeat left center;text-indent:-999px}
查看更多
登录 后发表回答