Center a large image of unknown size inside a smaller div with overflow hidden

What about this:

.img {
   position: absolute;
   left: 50%;
   top: 50%;
   -webkit-transform: translateY(-50%) translateX(-50%);
}

This assumes that the parent div is positioned relatively. I think this works if you want the .img relatively positioned rather than absolutely. Just remove the position: absolute and change top/left to margin-top and margin-left.

You’ll probably want to add browser support with transform, -moz-transform etc.

Leave a Comment