How to scale an image with css to fill a div keeping aspect ratio?

后端 未结 6 1903
情深已故
情深已故 2021-02-13 15:10

I\'d like to fill a div with an img, keeping aspect ratio and stretching either width or height as much as required to fit in.

6条回答
  •  日久生厌
    2021-02-13 15:49

    To keep an image's aspect ratio, just specify one dimension:

    div {
        width: 80px;
        height: 80px;
        border: 2px solid red;
        overflow: hidden;
    }
    
    img {
        height: 100%;
    }
    

    This will produce the following effect:

    However, as you can see, the kitten is not central, but you can use Flex box to sort this out.

    div {
        width: 80px;
        height: 80px;
        border: 2px solid red;
        justify-content: center;
        display: flex;
        flex-direction: row;
    }
    
    img {
        flex: 1;
        height: 100%;
    }
    

提交回复
热议问题