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

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

    <div id="container">
        <img src="something.jpg" alt="" />
    </div>
    
    <script type="text/javascript">
    (function() {
    
    var img = document.getElementById('container').firstChild;
    img.onload = function() {
        if(img.height > img.width) {
            img.height = '100%';
            img.width = 'auto';
        }
    };
    
    }());
    </script>
    

    CSS

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

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

    0 讨论(0)
  • 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%);
    }
    
    0 讨论(0)
  • 2020-11-28 02:25

    you can use class "img-fluid" for newer version i.e Bootstrap v4.

    and can use class "img-responsive" for older version like Bootstrap v3.

    Usage:-

    img tag with :-

    class="img-fluid"

    src="..."

    0 讨论(0)
  • 2020-11-28 02:26

    Using CSS only:

    div > img {
      width: auto;
      height : auto;
      max-height: 100%;
      max-width: 100%;
    }
    
    0 讨论(0)
  • 2020-11-28 02:27

    I was having a lot of problems to get this working, every single solution I found didn't seem to work.

    I realized that I had to set the div display to flex, so basically this is my CSS:

    div{
    display: flex;
    }
    
    div img{ 
    max-height: 100%;
    max-width: 100%;
    }
    
    0 讨论(0)
  • 2020-11-28 02:34

    Use max-height:100%; max-width:100%; for the image inside the div.

    0 讨论(0)
提交回复
热议问题