如何调整img标签的大小合适?
我想在小窗口中显示图像,但我需要保存图像的比例(我仍然希望人们知道它是什么)。 例如,假设图像为 1000X200 像素,并且有一个 div 定义为: 高度:100px; 宽度:100px; 所以我希望图像会这样写:
<img src="asd.jpg" height=20 width=100 />
不
<img src="asd.jpg" height=100 width=100 />
或不
<img src="asd.jpg"/>
然后有滚动..
我可以使用百分比,但我该怎么做..(它甚至可以单独使用百分比吗?)
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:
<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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您在 CSS 中设置
max-height
和max-width
,现代浏览器会将其限制为该大小,但保持正确的宽高比:If you set
max-height
andmax-width
in CSS, modern browsers will restrict it to that size but keep the aspect ratio correct:如果您的父
div
设置了width
和height
,您可以设置img< 的最大宽度和最大高度/code> 到
100%
:(对于移动浏览器等,将图像最大宽度设置为 100% 始终是一个好习惯。)
If your parent
div
has a setwidth
andheight
, you could set the max-width and max-height of theimg
to100%
:(It's always a good practice to give images max-width of 100%, for mobile browsers etc.)
如果您使用 javascript,您可以简单地获取图像的高度和宽度,然后将其除以另一个以获得比率,然后将 div 的高度和宽度乘以该比率,然后将 img 尺寸设置为这些数字。
显然,这是一种非常简单的说法,但我也不确定您是否想使用 JS 来完成此操作还是使用严格的 CSS 解决方案。
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.
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.