principal-ideal-domain
principal-ideal-domain

Reputation: 4266

How to automatically crop and center an image in div container

This is my html code

<div><img src="picture1.jpg" /></div>
<div><img src="picture2.jpg" /></div>
<div><img src="picture3.jpg" /></div>

My div containers have certain fixed dimensions:

div{
    width: 400px;
    height: 400px;
    object-fit: cover;
    overflow: hidden;
}
img{
    height:100%;
    width: 100%;
    display: block;
}

And I want to show as much of the middle of the image as possible inside the div containers (and crop the rest of the image away). So depending on the dimension of the image I want either to crop a little bit left and right from the image or top and bottom. Such that the biggest square within the image is shown. This square shall be centered and of course scaled accordingly.

I tried a lot and read a lot of threads before. For example this one. The problem is that nothing works for me parallel for different image dimensions (keep in mind that I don't want to adapt the code for different images). I want one code for all!

The html code shall be as it is. Only the css shall be adapted to make it work (so I don't want to use background images). But I'm open for fancy state of the art CSS stuff. Use flex layout or whatever you want!

Upvotes: 0

Views: 2411

Answers (2)

Jorge Monte
Jorge Monte

Reputation: 23

My solution would be simple:

div {
  width: 200px; /* or whatever size you need */
  height: 200px; /* or whatever size you need */
  position: relative;
  overflow: hidden;
}

div img {
  max-width: 100%;
  height: auto;
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div><img src="https://via.placeholder.com/300x600.jpg"></div>

The bad part of this solution is if any of the images have a very different ratio. In this case, the combination of min-height (for example) with the same size of the div would be necessary.

Upvotes: 0

tacoshy
tacoshy

Reputation: 13002

add object-fit: cover; to the image to fill the given size while not stretching the image. Also use height: 100%; width: 100%; to make sure that the image only take the given space.

The image will be centered by default.

img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

/* for demonstration only */

div {
  margin-bottom: 20px;
}

div:nth-of-type(1) {
  width: 200px;
  height: 50px;
}

div:nth-of-type(2) {
  width: 200px;
  height: 100px;
}

div:nth-of-type(3) {
  width: 200px;
  height: 200px;
}
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>
<div><img src="https://www.tacoshy.de/Images/Yoshi/IMAG0735.jpg"></div>

Upvotes: 5

Related Questions