Scale image to fit a bounding box

前端 未结 13 1904
轻奢々
轻奢々 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 11:10

    Another solution without background image and without the need for a container (though the max sizes of the bounding box must be known):

    img{
      max-height: 100px;
      max-width: 100px;
      width: auto;    /* These two are added only for clarity, */
      height: auto;   /* as the default is auto anyway */
    }
    


    If a container's use is required, then the max-width and max-height can be set to 100%:

    img {
        max-height: 100%;
        max-width: 100%;
        width: auto; /* These two are added only for clarity, */
        height: auto; /* as the default is auto anyway */
    }
    
    div.container {
        width: 100px;
        height: 100px;
    }
    

    For this you would have something like:

    <table>
        <tr>
            <td>Lorem</td>
            <td>Ipsum<br />dolor</td>
            <td>
                <div class="container"><img src="image5.png" /></div>
            </td>
        </tr>
    </table>
    
    0 讨论(0)
提交回复
热议问题