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

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

    You will need some JavaScript to prevent cropping if you don't know the dimension of the image at the time you're writing the css.

    HTML & JavaScript

    CSS

    #container {
       width: 48px;
       height: 48px;
    }
    
    #container img {
       width: 100%;
    }
    

    If you use a JavaScript Library you might want to take advantage of it.

提交回复
热议问题