Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centre and crop an image inside a div [duplicate]

Tags:

html

css

image

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?

like image 925
user2397282 Avatar asked Jul 24 '16 09:07

user2397282


People also ask

How do I center a div inside an image?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.

How do I crop an image in a div?

Using width, height and overflow to crop images in CSSAdd a div can give it class container. Set width and height to 150px then set the overflow to hidden. Use margin to position the image based on your needs. In this case, set it to -100px 0 0 -150px.

How do I crop an image in the center?

Specify the width and height properties. Add the background-image property and set the background-position to "center center". Add the background-repeat property with the "no-repeat" value.


1 Answers

HTML:

<div>
  <img src="https://picsum.photos/600/500" />
</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

like image 167
ristapk Avatar answered Oct 29 '22 21:10

ristapk