Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center image element in parent div

Tags:

html

css

image

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; }
like image 334
Caspert Avatar asked Aug 25 '13 12:08

Caspert


1 Answers

In case anyone lands up here looking for a solution, here's one using display: flex.

.box {
   display:flex;
   justify-content: center;
   align-items: center;
   background: green;
   border: 2px solid red;
   height: 100%;
   width: 450px;
   overflow: hidden;   
}
.box img {
  justify-content: center;
  align-items: center;
}
like image 161
flamesquirrel Avatar answered Oct 06 '22 00:10

flamesquirrel