center image in div with overflow hidden

Most recent solution:

HTML

<div class="parent">
    <img src="image.jpg" height="600" width="600"/>
</div>

CSS

.parent {
    width: 200px;
    height: 200px;
    overflow: hidden;
    /* Magic */
    display: flex;
    align-items: center; /* vertical */
    justify-content: center; /* horizontal */
}

You should make the container relative and give it a height as well and you're done.

http://jsfiddle.net/jaap/wjw83/4/

.main {
  width: 300px;
  margin: 0 auto;
  overflow: hidden;
  position: relative;
  height: 200px;
}

img.absolute {
  left: 50%;
  margin-left: -200px;
  position: absolute;
}
<div class="main">
  <img class="absolute" src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />
</div>
<br />
<img src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />

If you want to you can also center the image vertically by adding a negative margin and top position: http://jsfiddle.net/jaap/wjw83/5/


Found this nice solution by MELISSA PENTA (https://www.localwisdom.com/)

HTML

<div class="wrapper">
   <img src="image.jpg" />
</div>

CSS

div.wrapper {
  height:200px;
  line-height:200px;
  overflow:hidden;
  text-align:center;
  width:200px;
}
div.wrapper img {
  margin:-100%;
}

Center any size image in div
Used with rounded wrapper and different sized images.

CSS

.item-image {
    border: 5px solid #ccc;
    border-radius: 100%;
    margin: 0 auto;
    height: 200px;
    width: 200px;
    overflow: hidden;
    text-align: center;
}
.item-image img {
    height: 200px;    
    margin: -100%;
    max-width: none;
    width: auto;    
}

Working example here codepen


None of the above solutions were working out well for me. I needed a dynamic image size to fit in a circular parent container with overflow:hidden

.circle-container {
    width:100px;
    height:100px;
    text-align:center;
    border-radius:50%;
    overflow:hidden;
}

.circle-img img {
  min-width:100px;
  max-width:none;
  height:100px;
  margin:0 -100%;
}

Working example here: http://codepen.io/simgooder/pen/yNmXer

Tags:

Html

Css

Center