Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale an image with css to fill a div keeping aspect ratio?

Tags:

html

css

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.

like image 590
membersound Avatar asked Aug 11 '15 13:08

membersound


2 Answers

the following did the trick:

    width:100%;
    height:100%;
    object-fit: cover;
    overflow: hidden;
like image 62
membersound Avatar answered Sep 29 '22 21:09

membersound


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%;
}
like image 29
cdMinix Avatar answered Sep 29 '22 22:09

cdMinix