首页 文章

计算父div的图像大小维持纵横比的逻辑[重复]

提问于
浏览
2

这个问题在这里已有答案:

让我举个例子来解释一下 .

Lets say I have an Image of size

960px X 668px

I have a div which holds this image. The div size is
154px X 75px

这个div可以有任何可变大小 .

If we see that the aspect ratio of image and the aspect ratio of the div 
that holds image are different.

我需要做的就是使用PHP调整大小和裁剪图像,使其占用原始大小的最大可能高度和宽度,并保持保存此图像的div的宽高比 . I just need a logic to calculate a percentage 应该乘以多少DIV宽度和高度,使得得到的尺寸更接近图像尺寸但不超过图像尺寸,并且纵横比将与DIV相同但不与图像相同 .

谢谢夏米拉

1 回答

  • 1

    好的,那么你需要检查你是否使用宽度比或高度比 .

    img.with / div.with = ratio_w
    img.height / div.height = ratio_h
    

    然后,较高的比率是您需要使用的比率,以确保您的图像适合div .

    以你的榜样,我们有

    ratio_w = 960 / 154 = 6.2
    ratio_h = 668 / 75 = 8.9
    

    ratio_h 是更高的,所以 ratio_h 是你的比例

    然后,为了适合您的div,这里是调整大小的计算

    960 / 8.9 = 108
    668 / 8.9 = 75
    

    逻辑与其他值相同 .


    如果没有调整大小的问题,我建议检查这个CSS属性

    background-size: contain;
    

相关问题