How to maintain aspect ratio using HTML IMG tag
我正在使用HTML的img标签在我们的应用程序中显示照片。 我已将其height和width属性都设置为64。我需要将任何图像分辨率(例如256x256、1024x768、500x400、205x246等)显示为64x64。 但是通过将img标签的height和width属性设置为64,就不能保持纵横比,因此图像看起来会失真。
供您参考,我的确切代码是:
1 | <img src="Runtime Path to photo" border="1" height="64" width="64"> |
不要设置高度和宽度。使用其中之一,将保持正确的纵横比。
1 2 3 4 5 6 7 | .widthSet { max-width: 64px; } .heightSet { max-height: 64px; } |
1 2 3 4 5 6 7 8 9 | <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 2 3 4 5 6 7 8 9 10 11 | div{ width: 200px; height:200px; border:solid } img{ width: 100%; height: 100%; object-fit: contain; } |
1 | <img src="https://upload.wikimedia.org/wikipedia/meta/0/08/Wikipedia-logo-v2_1x.png"> |
将图像的
1 2 3 4 5 6 | img { max-width:64px; max-height:64px; width:auto; height:auto; } |
小提琴
如果要在64x64px"帧"中显示任意大小的图像,则可以使用内联块包装器并对其进行定位,就像这种小提琴一样。
1 2 | <img src="Runtime Path to photo" style="border: 1px solid #000; max-width:64px; max-height:64px;"> |
列出的方法均未将图像缩放到适合框的最大尺寸,同时又保留了所需的宽高比。
这不能通过IMG标签来完成(至少不是没有JavaScript的话),但是可以按照以下步骤完成:
1 |
将图像包装在尺寸为64x64的
1 | <img src="Runtime path" style="width: inherit" /> |
尝试这个:
1 | <img src="Runtime Path to photo" border="1" height="64" width="64" object-fit="cover"> |
添加object-fit =" cover"将强制图像占用空间而不会丢失宽高比。
为什么不使用单独的CSS文件来保持要显示图像的高度和宽度?这样,您可以一定提供宽度和高度。
例如:
1 2 3 4 | image { width: 64px; height: 64px; } |