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!

2

7 Answers

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.

7

text-align: center will only work for horizontal centering. For it to be in the complete center, vertical and horizontal you can do the following :

div { position: relative; } div img { position: absolute; top: 50%; left: 50%; margin-left: [-50% of your image's width]; margin-top: [-50% of your image's height]; } 
4

A very simple and elegant solution to this is provided by W3C. Simply use the margin:0 auto declaration as follows:

.top_image img { margin:0 auto; } 

More information and examples from W3C.

1
<div> <div> <img src="" alt="tall image" /> </div> </div> <hr /> <div> <div> <img src="" alt="wide image" /> </div> </div> 

CSS

img { max-width: 100%; max-height: 100%; display: block; margin: auto auto; } .outer { border: 1px solid #888; width: 100px; height: 100px; } .inner { display:table-cell; height: 100px; width: 100px; vertical-align: middle; } 

I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example:

1

I hope this would be helpful:

.top_image img{ display: block; margin: 0 auto; } 
1

This took me way too long to figure out. I can't believe nobody has mentioned center tags.

Ex:

<center><img src = "yourimage.png"/></center> 

and if you want to resize the image to a percentage:

<center><img src = "yourimage.png" width = "75%"/></center> 

GG America

3