How do I vertically center an img in a div?

ぃ、小莉子 提交于 2019-12-23 04:28:08

问题


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.


回答1:


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/




回答2:


Add a rule in your css class:

 {vertical-align:middle;}



回答3:


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>



回答4:


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



来源:https://stackoverflow.com/questions/13785947/how-do-i-vertically-center-an-img-in-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!