How do I fit an image (img) inside a div and keep the aspect ratio?

后端 未结 12 2049
广开言路
广开言路 2020-11-28 01:31

I have a 48x48 div and inside it there is an img element, I want to fit it into the div without losing any part, in the mean time the ratio is kept, is it achievable using h

12条回答
  •  醉酒成梦
    2020-11-28 02:24

    For me, the following CSS worked (tested in Chrome, Firefox and Safari).

    There are multiple things working together:

    • max-height: 100%;, max-width: 100%; and height: auto;, width: auto; make the img scale to whichever dimension first reaches 100% while keeping the aspect ratio
    • position: relative; in the container and position: absolute; in the child together with top: 50%; and left: 50%; center the top left corner of the img in the container
    • transform: translate(-50%, -50%); moves the img back to the left and top by half its size, thus centering the img in the container

    CSS:

    .container {
        height: 48px;
        width: 48px;
    
        position: relative;
    }
    
    .container > img {
        max-height: 100%;
        max-width: 100%;
        height: auto;
        width: auto;
    
        position: absolute;
        top: 50%;
        left: 50%;
    
        transform: translate(-50%, -50%);
    }
    

提交回复
热议问题