The accepted answer probably works for some situations, but it depends on the ratio of the rectangle and any predetermined styles.
I use this method because it's more compatible than solutions only using object-fit
:
.image-cropper {
width: 150px;
height: 150px;
position: relative;
overflow: hidden;
border-radius: 50%;
border:2px solid #f00;
}
/* Common img styles in web dev environments */
img {
height: auto;
max-width: 100%;
}
/* Center image inside of parent */
img.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* For horizontal rectangles */
img.horizontal {
height: 100%;
width: auto;
max-width: 9999px; /* max-content fall back */
max-width: max-content;
}
<div class="image-cropper">
<img src="https://via.placeholder.com/300x600" class="center" />
</div>
<div class="image-cropper">
<img src="https://via.placeholder.com/600x300" class="horizontal center" />
</div>
If you run the snippet you can see, for horizontal rectangles we add another class .horizontal
.
We override max-width
to allow the img to go larger than 100% of the width. This preserves the aspect ratio, preventing the image from stretching.
However, the image will not be centered and that's where the .centered
class comes in. It uses a great centering trick to absolute position the image in the center both vertically and horizontally.
More information on the centering at CSS Tricks
More than likely you won't always know what ratio the image will be, so this is why I'd suggest using javascript to target the img and add the .horizontal
class if needed.
Here is a stack overflow answer that would work