249

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!

Nima Derakhshanjan
  • 1,368
  • 9
  • 24
  • 35
joschua011
  • 4,077
  • 4
  • 19
  • 25

7 Answers7

605

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.

Clemens Tolboom
  • 1,664
  • 17
  • 28
Dyin
  • 6,494
  • 6
  • 42
  • 65
29

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];
}
Maxime Fabre
  • 2,242
  • 3
  • 20
  • 24
11

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.

Baby Groot
  • 4,617
  • 39
  • 52
  • 69
Phil Thomas
  • 119
  • 1
  • 3
9
<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;
}
Uyghur Lives Matter
  • 17,261
  • 40
  • 105
  • 135
Ads
  • 1,964
  • 1
  • 23
  • 33
7

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/

Jay
  • 1,365
  • 1
  • 17
  • 29
5

I hope this would be helpful:

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

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