Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Center and Keep Aspect Ratio of Image in Div

Tags:

css

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.

like image 245
user3448267 Avatar asked Feb 13 '23 01:02

user3448267


2 Answers

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;
}
like image 105
Anonymous Avatar answered Feb 24 '23 07:02

Anonymous


for one looking for horizontally center.

Solution of @sibbl worked, but there is still some pixels on the top of image in horizontal case.

I have imporoved @Anoymous code

HTML:

<div class="imageHolder">
    <img src="http://lorempixel.com/g/800/400">
</div>
<div class="imageHolder">
    <img src="http://lorempixel.com/g/800/800">
</div>
<div class="imageHolder">
   <img src="http://lorempixel.com/g/400/800">
</div>

CSS:

.imageHolder {
    width: 300px;
    height: 300px;
    background-color:#CCCCCC;
    margin:10px;
    display:inline-block;
    float:left;
    position:relative;
}
.imageHolder img {
    max-width: 100%;
    max-height:100%;
    margin: auto;
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
}

JSFiddle - DEMO

like image 44
vanduc1102 Avatar answered Feb 24 '23 08:02

vanduc1102