Scale image to fit a bounding box

前端 未结 13 2089
轻奢々
轻奢々 2020-11-27 10:17

Is there a css-only solution to scale an image into a bounding box (keeping aspect-ratio)? This works if the image is bigger than the container:

img {
  max-         


        
13条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 10:51

    I have used table to center image inside the box. It keeps aspect ratio and scales image in a way that is totally inside the box. If the image is smaller than the box then it is shown as it is in the center. Below code uses 40px width and 40px height box. (Not quite sure how well it works because I removed it from another more complex code and simplified it little bit)

    .SmallThumbnailContainer {
      display: inline-block;
      position: relative;
      float: left;
      width: 40px;
      height: 40px;
      border: 1px solid #ccc;
      margin: 0px;
      padding: 0px;
    }
    
    .SmallThumbnailContainer {
      width: 40px;
      margin: 0px 10px 0px 0px;
    }
    
    .SmallThumbnailContainer tr {
      height: 40px;
      text-align: center;
    }
    
    .SmallThumbnailContainer tr td {
      vertical-align: middle;
      position: relative;
      width: 40px;
    }
    
    .SmallThumbnailContainer tr td img {
      overflow: hidden;
      max-height: 40px;
      max-width: 40px;
      vertical-align: middle;
      margin: -1px -1px 1px -1px;
    }
    OP's SO avatar image used as a sample jpg because it is hosted on SO, thus always available

    Note: the native thumbnail size in this snippet is 32px x 32px, which is smaller than its 40px x 40px container. If the container is instead sized smaller than the thumbnail in any dimension, say 40px x 20px, the image flows outside the container in the dimensions that are smaller than the corresponding image dimension. The container is marked by a gray 1px border.

提交回复
热议问题