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

后端 未结 6 1915
情深已故
情深已故 2021-02-13 15:10

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.

6条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 15:46

    Not sure if anyone still looking at this post. I came across this while I was looking for a way to fit a image into a < div > without getting the unwanted white space around the image, because I was using hover & stick-out effect. I was inspired by Matt's solution. Instead of

    .thumb {
    max-width:100%;
    height:auto;}
    

    I added

    .thumb {
    max-width:100%;
    max-height:100%;
    height:auto;}
    

    Now my images fit in to the < div > perfectly without having those white space stick out with the image.

提交回复
热议问题