如何使用百分比作为参数调整 HTML 中的图像大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12770021/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:13:12  来源:igfitidea点击:

How to resize image in HTML using percentage as parameters?

htmlcssimage

提问by Borut Flis

I would like to resize an image on my website. I know how to do it by either resizing the image before or calculating the width and height and setting the values in pixels. But I use the same picture multiple times with different dimmensions, so it would take me less time if I could resize the image relatively to its own size.

我想调整我网站上的图像大小。我知道如何通过之前调整图像大小或计算宽度和高度并以像素为单位设置值来做到这一点。但是我多次使用不同尺寸的同一张图片,所以如果我可以相对于自己的大小调整图像的大小,我会花费更少的时间。

<img src='images/logo-beta.png' id="logo" height="75%" width="75%"/>

I have tried this, however the problem is that the size is set relative to its parent element.

我试过这个,但是问题是大小是相对于它的父元素设置的。

回答by danwellman

There's no way to do what you want automatically using HTML or CSS alone. You'll need to use JavaScript to get the image's dimensions, then calculate a percentage of those dimensions and reapply them to the image in pixels

单独使用 HTML 或 CSS 无法自动执行您想要的操作。您需要使用 JavaScript 来获取图像的尺寸,然后计算这些尺寸的百分比并将它们重新应用于图像(以像素为单位)

回答by amustill

There is a method, but it isn't perfect. It requires a wrapping element whose display is set to 'inline-block' and the image is resized using 'max-width'.

有一种方法,但并不完美。它需要一个包装元素,其显示设置为“inline-block”,并且使用“max-width”调整图像大小。

The issue is that the parent element retains the image's original width, which could cause problems depending on your requirements.

问题是父元素保留了图像的原始宽度,这可能会导致问题,具体取决于您的要求。

Example: http://jsfiddle.net/amustill/GnEw5/

示例:http: //jsfiddle.net/amustill/GnEw5/