How to maintain aspect ratio using HTML IMG tag

前端 未结 10 1462
面向向阳花
面向向阳花 2020-12-23 02:42

I am using an img tag of HTML to show a photo in our application. I have set both its height and width attribute to 64. I need to show any image resolution (e.g. 256x256, 10

相关标签:
10条回答
  • 2020-12-23 03:18

    Wrap the image in a div with dimensions 64x64 and set width: inherit to the image:

    <div style="width: 64px; height: 64px;">
        <img src="Runtime path" style="width: inherit" />
    </div>
    
    0 讨论(0)
  • 2020-12-23 03:19

    Don't set height AND width. Use one or the other and the correct aspect ratio will be maintained.

    .widthSet {
        max-width: 64px;
    }
    
    .heightSet {
        max-height: 64px;
    }
    <img src="http://placehold.it/200x250" />
    
    <img src="http://placehold.it/200x250" width="64" />
    
    <img src="http://placehold.it/200x250" height="64" />
    
    <img src="http://placehold.it/200x250" class="widthSet" />
    
    <img src="http://placehold.it/200x250" class="heightSet" />

    0 讨论(0)
  • 2020-12-23 03:22

    With css:

    .img {
        display:table-cell;
        max-width:...px;
        max-height:...px;
        width:100%;
    }
    
    0 讨论(0)
  • 2020-12-23 03:24

    Use object-fit: contain in css of html element img.

    ex:

    img {
        ...
        object-fit: contain
        ...
    }
    
    0 讨论(0)
提交回复
热议问题