首页 文章

如何使用HTML IMG标记保持宽高比

提问于
浏览
90

我正在使用HTML的img标签在我们的应用程序中显示照片 . 我已将其高度和宽度属性设置为64.我需要将任何图像分辨率(例如256x256,1024x768,500x400,205x246等)显示为64x64 . 但是通过将img标记的height和width属性设置为64,它不会保持纵横比,因此图像看起来会失真 .

供您参考我的确切代码是:

<img src="Runtime Path to photo" border="1" height="64" width="64">

7 回答

  • 42

    将图像包裹在尺寸为64x64的 div 中,并将 width: inherit 设置为图像:

    <div style="width: 64px; height: 64px;">
        <img src="Runtime path" style="width: inherit" />
    </div>
    
  • 97

    为什么不使用单独的CSS文件来维护要显示的图像的高度和宽度?这样,您就可以提供宽度和高度 .

    例如:

    image {
           width: 64px;
           height: 64px;
           }
    
  • 33

    widthheight 的图像设置为 auto ,但同时限制 max-widthmax-height

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

    Fiddle

    如果要在64x64px "frames"中显示任意大小的图像,可以使用内联块包装和定位,如in this fiddle .

  • 9

    列出的方法都没有将图像缩放到适合框的最大可能尺寸,同时保留所需的宽高比 .

    这不能用IMG标签完成(至少没有一点JavaScript),但可以按如下方式完成:

    <div style="background:center no-repeat url(...);background-size:contain;width:...;height:..."></div>
    
  • 0

    不要设置高度和宽度 . 使用其中一个,将保持正确的宽高比 .

    .widthSet {
        max-width: 100px;
    }
    
    .heightSet {
        max-height: 100px;
    }
    
    <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" />
    
  • 1

    这是样本之一

    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>
    
  • 33
    <img src="Runtime Path to photo" style="border: 1px solid #000; max-width:64px; max-height:64px;">
    

相关问题