简体   繁体   English

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

[英]How to resize image in HTML using percentage as parameters?

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. 但是我使用不同的dimmensions多次使用相同的图片,所以如果我可以相对于自己的大小调整图像大小,我将花费更少的时间。

<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. 我试过这个,但问题是大小是相对于其父元素设置的。

There's no way to do what you want automatically using HTML or CSS alone. 单独使用HTML或CSS无法自动执行您想要的操作。 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 您需要使用JavaScript来获取图片的尺寸,然后计算这些尺寸的百分比并将其重新应用于图像(以像素为单位)

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'. 它需要一个包装元素,其显示设置为“内联块”,并使用“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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM