Resize to fit image in div, and center horizontally and vertically

Benjamin Crouzier picture Benjamin Crouzier · Jun 26, 2013 · Viewed 110.5k times · Source

I have an image in a div. I would like the image to resize to fit the div, and be horizontally and vertically centered. I would like a solution that works in ie >= 8.

Answer

Benjamin Crouzier picture Benjamin Crouzier · Jun 26, 2013

This is one way to do it:

Fiddle here: http://jsfiddle.net/4Mvan/1/

HTML:

<div class='container'>
    <a href='#'>
    <img class='resize_fit_center'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
    </a>
</div>

CSS:

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}
.resize_fit_center {
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}