Scale image to fit a bounding box

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

    The cleanest and simplest way to do this:

    First some CSS:

    div.image-wrapper {
        height: 230px; /* Suggestive number; pick your own height as desired */
        position: relative;
        overflow: hidden; /* This will do the magic */
        width: 300px; /* Pick an appropriate width as desired, unless you already use a grid, in that case use 100% */
    }
    img {
        width: 100%;
        position: absolute;
        left: 0;
        top: 0;
        height: auto;
    }
    

    The HTML:

    This should do the trick!

提交回复
热议问题