How do I vertically center an img in a div?

2019-06-06 20:37发布

I have an <img> that I want to center in a <div>. All previous answers I've found here use some hack or require you to know the image's width, which varies in my case.

Horizontal centering with text-align: center on the parent is easy. I can't figure out how to vertically align.

jsFiddle example

FYI Facebook does this well using just HTML and CSS. So please no <table> or javascript hacks. It looks like they are using something with line-height to make their <img> vertically center.

4条回答
叼着烟拽天下
2楼-- · 2019-06-06 20:56

As @kobi mentioned in a comment, all you need to do is set a line-height on your containing div. No tables.

jsFiddle example of vertically centered image

查看更多
爷、活的狠高调
3楼-- · 2019-06-06 20:57
html, body, #wrapper {
   height:100%;
   width: 100%;
   margin: 0;
   padding: 0;
   border: 0;
}
#wrapper td {
   vertical-align: middle;
   text-align: center;
}


<html>
<body>
   <table id="wrapper">
      <tr>
         <td><img src="logo.png" alt="" /></td>
      </tr>
   </table>
</body>
</html>
查看更多
Lonely孤独者°
4楼-- · 2019-06-06 21:19

Remember that vertical-align: middle; is not to useful on its own, you also need to set the line-height: line-height:400px;.

This is useful if you have no other text in your <div> (except maybe a single line).

Working example: http://jsfiddle.net/kobi/ZfMYy/5/

查看更多
【Aperson】
5楼-- · 2019-06-06 21:20

Add a rule in your css class:

 {vertical-align:middle;}
查看更多
登录 后发表回答