[html] Center image in div horizontally

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!

This question is related to html css

The answer is


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: http://jsfiddle.net/Tv9mG/


<div class="outer">
    <div class="inner">
        <img src="http://1.bp.blogspot.com/_74so2YIdYpM/TEd09Hqrm6I/AAAAAAAAApY/rwGCm5_Tawg/s320/tall+copy.jpg" alt="tall image" />
    </div>
</div>
<hr />
<div class="outer">
    <div class="inner">
        <img src="http://www.5150studios.com.au/wp-content/uploads/2012/04/wide.jpg" 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;
}

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.


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


I hope this would be helpful:

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

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];
}