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

后端 未结 12 2055
广开言路
广开言路 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:15

    Setting the photo as a background image will give us more control over size and placement, leaving the img tag to serve a different purpose...

    Below, if we want the div to be the same aspect ratio as the photo, then placeholder.png is a small transparent image with the same aspect ratio as photo.jpg. If the photo is a square, it's a 1px x 1px placeholder, if the photo is a video thumbnail, it's a 16x9 placeholder, etc.

    Specific to the question, use a 1x1 placeholder to maintain the div's square ratio, with a background image using background-size to maintain the photo's aspect ratio.

    I used background-position: center center; so the photo will be centered in the div. (Aligning the photo in the vertical center or bottom would get ugly with the photo in the img tag.)

    div {
        background: url(photo.jpg) center center no-repeat;
        background-size: contain;
        width: 48px; // or a % in responsive layout
    }
    img {
        width: 100%;
    }
    
    

    To avoid an extra http request, convert the placeholder image to a data: URL.

    
    

提交回复
热议问题