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.
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.
As @kobi mentioned in a comment, all you need to do is set a
line-height
on your containingdiv
. No tables.jsFiddle example of vertically centered image
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/
Add a rule in your css class: