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

后端 未结 6 1899
情深已故
情深已故 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:43

    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%;
    }
    

提交回复
热议问题