Center image in div horizontally

joschua011 picture joschua011 · Apr 2, 2012 · Viewed 444.6k times · Source

I have an img in a div (class="top_image") and I want this image to be exactly in the middle of the div but nothing I try works...

Thanks for any help!

Answer

Dyin picture Dyin · Apr 16, 2013

Every solution posted here assumes that you know the dimensions of your img, which is not a common scenario. Also, planting the dimensions into the solution is painful.

Simply set:

/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;

or

/* for the img inside your div */
display: block;
margin: 0 auto;

That's all.

Note, that you'll also have to set an initial min-width for your outer div.