简体   繁体   English

知道px的高度和宽度,保持div的纵横比(以%为单位)

[英]Maintain aspect ratio of div in %, knowing the height and width in px

I'm adding a background image to a div. 我要向div添加背景图片。

<div class="image" style="background-image: url(...)>
</div>

The CSS is dynamic. CSS是动态的。 It could be for example... 例如...

.image {
   width: 65%;
   height: ? (trying to figure out the value)
}

I'm trying to calculate the height in js, in order to maintain the aspect ratio of the image. 我正在尝试在js中计算高度,以保持图像的长宽比。

How can I set a correct height value in CSS, based the width in CSS which is set in %, to maintain the image size ratio if I know the width and height of the original image in px? 如果我知道原始图像的宽度和高度(以px为单位),如何基于CSS的宽度(以%设置)在CSS中设置正确的高度值,以保持图像尺寸比率?

The problem would look something like this: 问题看起来像这样:

Image width = 300px 图片宽度= 300像素

Image height = 520px 图像高度= 520px

Width in CSS = 65% CSS中的宽度= 65%

Height in CSS to maintain aspect ratio = ? CSS中保持纵横比的高度=?

I cannot use the width of the parent container for calculations. 我无法使用父容器的宽度进行计算。

I cannot grab the dynamic image width in px using offsetWidth . 我无法使用offsetWidth获取以px为单位的动态图像宽度。

I cannot just use the image in the div. 我不能只在div中使用图像。

You do not need to know the original dimensions of the image. 您无需知道图像的原始尺寸。 Setting one dimension for the image automatically sets the other such that the aspect ratio is maintained. 为图像设置一个尺寸会自动设置另一个尺寸,以保持宽高比。 Here is an example: 这是一个例子:

Original Image (400px x 300px) 原始图片(400像素x 300像素)

 <img src="https://i.stack.imgur.com/lKtag.png"/> 

Resized Image (40% of the container's width) 调整大小的图像(占容器宽度的40%)

 <img src="https://i.stack.imgur.com/lKtag.png" style="width:40%"/> 

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

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