Center image element in parent div
How I can set center an image element inside a parent div? I would like to do this so that the middle of the image is always in the center of his parent. Also I want the image to always have 100% height (note: I don't want to stretch the image width).
See here for an example: http://jsfiddle.net/Ex5ax/5/
<div class="box">
<img src='featured.jpg' />
</div>
CSS:
.box { height: 100%; width: 450px; border: 2px solid red; background: green; overflow: hidden; }
.box img { height: 100%; width: auto; text-align: center; }
Add text-align: center;
CSS declaration to the parent .box
instead of the children .box img
.
.box {
height: 100%;
width: 450px;
border: 2px solid red;
background: green;
overflow: hidden;
text-align: center; /* align center all inline elements */
}
Here is the Fiddle.
Update
It seems there's also a 5px
gap under the image, It belongs to the line height reserved characters. To remove that from inline elements like <img>
you can use vertical-align: bottom
:
.box img {
height: 100%;
width: auto;
vertical-align: bottom; /* <-- fix the vertical gap */
}
JSFiddle Demo #2
You'll need to move the text-align: center;
from the CSS for the image to the CSS for its parent div, so your CSS looks like this:
.box {
height: 100%;
width: 450px;
border: 2px solid red;
background: green;
overflow: hidden;
text-align:center
}
.box img {
height: 100%;
width: auto;
}
And that's it!