Scale image to fit a bounding box

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

    Lorem Ipsum
    dolor

提交回复
热议问题