Html 如何调整到合适的 img 标签?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5748593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resize to the img tag appropriate?
提问by Nir
I want to show an image in small windows but i need to save on the ratio of the image(I still want that people can know what it is). For example lets say that the image is 1000X200 pixels, and there's a div that defined as: height: 100px; width: 100px; So I want that the image will wrote like that:
我想在小窗口中显示图像,但我需要保存图像的比例(我仍然希望人们可以知道它是什么)。例如,假设图像是 1000X200 像素,并且有一个 div 定义为:height: 100px; 宽度:100px;所以我希望图像会这样写:
<img src="asd.jpg" height=20 width=100 />
and not
并不是
<img src="asd.jpg" height=100 width=100 />
or not
或不
<img src="asd.jpg"/>
and then there's scrolls..
然后有卷轴..
I can work with percentages, but how do I do it.. (and does it even work with percentages alone?)
我可以使用百分比,但我该怎么做..(它甚至可以单独使用百分比吗?)
回答by David Fullerton
If you set max-height
and max-width
in CSS, modern browsers will restrict it to that size but keep the aspect ratio correct:
如果您在 CSS 中设置max-height
和max-width
,现代浏览器会将其限制为该大小,但保持纵横比正确:
<img src="asd.jpg" style="max-height: 100px; max-width: 100px;" />
回答by Rudie
If your parent div
has a set width
and height
, you could set the max-width and max-height of the img
to 100%
:
如果您的父母div
有一组width
and height
,您可以将 the 的 max-width 和 max-height 设置img
为100%
:
div {
width: 100px;
height: 100px;
}
div > img {
max-width: 100%;
max-height: 100%;
}
(It's always a good practice to give images max-width of 100%, for mobile browsers etc.)
(对于移动浏览器等,将图像最大宽度设置为 100% 始终是一个好习惯。)
回答by Munzilla
If you use javascript, you could simply get the height and width of the image and divide one by the other to get a ratio, then multiply the height and width of the div against that ratio, then set the img dimensions to those numbers.
如果您使用 javascript,您可以简单地获取图像的高度和宽度,然后将其除以另一个以获得比率,然后将 div 的高度和宽度与该比率相乘,然后将 img 尺寸设置为这些数字。
Obviously that's a very simplistic way to say it, but I'm also not sure if you want to do this with JS or use a strictly CSS solution.
显然,这是一种非常简单的表达方式,但我也不确定您是要使用 JS 执行此操作还是使用严格的 CSS 解决方案。