user3448267 user3448267 - 1 month ago 8
CSS Question

Auto Center and Keep Aspect Ratio of Image in Div

I m trying to center an image in a div while keeping the aspect ratio - I m using this code but somehow its not aligning the item in the center (top/bottom center). If possible using only CSS.

The size of the image is not known since its using max widths!

JSfiddle: http://jsfiddle.net/L41wpza6/2/

#imageHolder {
width: 400px;
height: 400px;
line-height: 400px;
background-color:#CCCCCC;
}

#imageHolder img {
max-width: 100%;
max-height:100%;
display: block;
margin: 0 auto;
vertical-align: middle;


}

Any help is appreciated! I am not sure what I am missing to make this work.

Answer

JSFiddle - DEMO

You should use display: inline-block; to #imageHolder img to vertical-align middle.

CSS display inline-block property allows elements to flow like inline elements but respect properties, such as width, like block elements and you can use display Inline-block to set vertical-align middle.

HTML:

<div id="imageHolder">
    <img src="http://www.discoverjb.com/wp-content/uploads/2014/07/IMG_1399.jpg">
</div>

CSS:

#imageHolder {
    width: 400px;
    height: 400px;
    line-height: 400px;
    background-color:#CCCCCC;
}
#imageHolder img {
    max-width: 100%;
    max-height:100%;
    display: inline-block; /* Instead of display: block; */
    margin: 0 auto;
    vertical-align: middle;
}