How do I vertically center an img in a div?

2019-06-06 20:33发布

问题:

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