Scale image to fit a bounding box

前端 未结 13 2017
轻奢々
轻奢々 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:52

    You can accomplish this with pure CSS and complete browser support, both for vertically-long and horizontally-long images at the same time.

    Here's a snippet which works in Chrome, Firefox, and Safari (both using object-fit: scale-down, and without using it):

    figure {
      margin: 0;
    }
    
    .container {
      display: table-cell;
      vertical-align: middle;
      width: 80px;
      height: 80px;
      border: 1px solid #aaa;
    }
    
    .container_image {
      display: block;
      max-width: 100%;
      max-height: 100%;
      margin-left: auto;
      margin-right: auto;
    }
    
    .container2_image2 {
      width: 80px;
      height: 80px;
      object-fit: scale-down;
      border: 1px solid #aaa;
    }
    Without `object-fit: scale-down`:
    
    



    Using `object-fit: scale-down`:


提交回复
热议问题