user2397282 user2397282 - 4 months ago 15
HTML Question

Centre and crop an image inside a div

I can't seem to find an answer to this, although some are close.

I have an image that I want to take out the middle of (crop it), a bit like this:

enter image description here

So it's perfectly in the middle and with the same aspect ratio.

All I have managed to do, is crop an image like so:

enter image description here

..where it's connected to the edges.

So basically, I want to have a div of fixed size, with an image inside. This image needs to be zoomed in and centred, with the overflow hidden.

How can I do this?

Answer

HTML:

<div>
  <img src="http://www.nature.org/cs/groups/webcontent/@web/@northamerica/documents/media/pygmy-rabbit-600x500.jpg" />
</div>

CSS:

div{
  position: relative;
  width: 300px;
  height: 300px;
  overflow: hidden;
}

img{
  position: absolute;
  top: -9999px;
  left: -9999px;
  right: -9999px;
  bottom: -9999px;
  margin: auto;
}

CODEPEN link: http://codepen.io/bra1N/pen/NArjNN

Comments