How to maintain aspect ratio using HTML IMG tag

前端 未结 10 1461
面向向阳花
面向向阳花 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:00

    here is the sample one

    div{
       width: 200px;
       height:200px;
       border:solid
     }
    
    img{
        width: 100%;
        height: 100%;
        object-fit: contain;
        }
    <div>
      <img src="https://upload.wikimedia.org/wikipedia/meta/0/08/Wikipedia-logo-v2_1x.png">
    </div>

    0 讨论(0)
  • 2020-12-23 03:03
    <img src="Runtime Path to photo"
         style="border: 1px solid #000; max-width:64px; max-height:64px;">
    
    0 讨论(0)
  • 2020-12-23 03:03

    None of the methods listed scale the image to the largest possible size that fits in a box while retaining the desired aspect ratio.

    This cannot be done with the IMG tag (at least not without a bit of JavaScript), but it can be done as follows:

     <div style="background:center no-repeat url(...);background-size:contain;width:...;height:..."></div>
    
    0 讨论(0)
  • 2020-12-23 03:04

    Set width and height of the images to auto, but limit both max-width and max-height:

    img {
        max-width:64px;
        max-height:64px;
        width:auto;
        height:auto;
    }
    

    Fiddle

    If you want to display images of arbitrary size in the 64x64px "frames", you can use inline-block wrappers and positioning for them, like in this fiddle.

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

    Try this:

    <img src="Runtime Path to photo" border="1" height="64" width="64" object-fit="cover">
    

    Adding object-fit="cover" will force the image to take up the space without losing the aspect ratio.

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

    Why don't you use a separate CSS file to maintain the height and the width of the image you want to display? In that way, you can provide the width and height necessarily.

    eg:

           image {
           width: 64px;
           height: 64px;
           }
    
    0 讨论(0)
提交回复
热议问题