center image in div with overflow hidden

Puyol picture Puyol · May 31, 2012 · Viewed 122k times · Source

I have an image of 400px and a div that is smaller (the width is not always 300px as in my example). I want to center the image in the div, and if there is an overflow, hide it.

Note: I must keep the position:absolute on the image. I'm working with css-transitions, and if I use position:relative, my image shakes a bit (https://web.archive.org/web/20120528225923/http://ta6.maxplus.be:8888/).

jsfiddle http://jsfiddle.net/wjw83/1/

Answer

Jaap picture Jaap · May 31, 2012

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/