Center an `<img>` in a `<div>`

Problem

How do I center an <img> in a containing <div>?

The usual margin-left: auto; margin-right: auto; isn't working.

The image can be larger than the container, and is scaled either horizontally or vertically by the max-width and max-height.

A jsfiddle with the below code: http://jsfiddle.net/9ShGj/1/

HTML:

<div class="container">
   <img src="http://www.yensa.com/fat/fat-dude10.jpg" />
</div>
<div class="container">
   <img src="http://oi43.tinypic.com/bje2wn.jpg" />
</div>

CSS:

.container {
 width: 200px;
 height: 200px;
 background: rgb(120, 120, 120);
 border: 1px solid red;
 margin: 5px;
}

.container img {
 max-width: 200px;
 max-height: 200px;
 margin-left: auto;
 margin-right: auto;
 vertical-align: middle;
}
Problem courtesy of: Don P

Solution

You can write like this:

CSS

div{
    width:200px;
    height:200px;
    border:1px solid red;
    text-align:center;
    line-height:200px;
}

img{
    vertical-align:middle;
}

HTML

<div>
    <img src="http://dummyimage.com/150x150/000/fff&text=dummy" >
</div>

Check this http://jsfiddle.net/dP89y/

Solution courtesy of: sandeep

Discussion

Unless you are making the img a block level element, you should be able to center it with:

.container { text-align: center; }
Discussion courtesy of: Chris Herbert

Image is not a block level element so need to convert it into block level element

So in your css add

.container img {
 display:block                /*ADD this line*/
 max-width: 200px;
 max-height: 200px;
 margin-left: auto;
 margin-right: auto;
 vertical-align: middle;
}

Also you need to consider following points

Doctype : check whether it is not in quirks mode.

Width of inner div or image must me less that width of parent div.

do check these things you will get your answer...All the best.

Discussion courtesy of: Rajiv Pingale

Update following CSS... vertical-align:middle; text-align:center

   .container {
        width: 200px;
        height: 200px;
        background: rgb(120, 120, 120);
        border: 1px solid red;
        margin: 5px;
        vertical-align:middle; text-align:center //add this
    }
Discussion courtesy of: Gaurav

This recipe can be found in it's original form on Stack Over Flow.