I'd like to fill a div with an img
, keeping aspect ratio and stretching either width or height as much as required to fit in.
<div style="width: 80px; height: 80px">
<img src="..." />
</div>
How could I achieve it? If the image is not quadratic, it must be "zoomed in" and either be scropped top-bottom or left-right, depending which side is the bigger one. Moreover the image should afterwards be centered, so that the corners get cut equally.
I tried (but no effect):
.thumb {
max-width:100%;
max-height:100%;
}
If I add additional width: 100%; height:100%;
, the images fit perfectly, but are resized not keeping aspect ratio
.
the following did the trick:
width:100%;
height:100%;
object-fit: cover;
overflow: hidden;
Using max-width
, the image will be contained inside the div, there will be no overflow.
If you use min-width
instead, the shorter side will be exactly 100% of the div while the other side can be longer.
To center the image, we can use translate and relative positioning.
The following code works.
div {
overflow: hidden;
}
.thumb {
min-width: 100%;
min-height: 100%;
transform: translate(-50%, -50%);
position: relative;
left: 50%;
top: 50%;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With