如何使并排图片等高(CSS/HTML)?

3

有两张图片,一张是300x400像素(高 x 宽),另一张是500x600。我该如何使它们并排显示,缩放后在屏幕上具有相同的高度,填满页面(或容器/ div)的整个宽度,而不改变任何一张图片的纵横比?

我想要一种HTML / CSS方法来实现这一点,如果可能的话,能够适用于超过2张图片的情况。目前,我手动计算每个图像的宽度(下面有数学公式)。

编辑:
我尝试做的事情的例子:

<img src="http://stackoverflow.com/content/img/so/logo.png"
     width="79%" style="float:left" border=1 />
<img src="http://stackoverflow.com/content/img/so/vote-favorite-off.png"
     width="20%" border=1 />

使用以下公式(或试错法)得出79/20的拆分比例。请注意,79 + 20 < 100 - 如果我将其设置为80/20,则由于边框而导致图像换行。如何在不进行任何计算的情况下完成此操作?浏览器应该能够为我完成这项工作。
ah1 = 300 // actual height of image 1
aw1 = 400 // actual width of image 1
ah2 = 500 // actual height of image 2
aw2 = 600 // actual width of image 2

// need to calculate these:
dw1 // display width of image 1, expressed as percent
dw2 // display width of image 2, expressed as percent
dw1 + dw2 == 100%

s1 = dw1 / aw1 // scale of image 1 (how much it has been shrunk)
s2 = dw2 / aw2

dh1 = ah1 * s1 // display height of image 1 = its actual height * its scale factor
dh2 = ah2 * s2

// need to solve this equality to get equal display heights:
            dh1 == dh2
       s1 * ah1 == s2 * ah2
dw1 / aw1 * ah1 == dw2 / aw2 * ah2
dw1 / aw1 * ah1 == (1 - dw1) / aw2 * ah2
dw1 * aw2 * ah1 == (1 - dw1) * aw1 * ah2
dw1 * aw2 * ah1 == aw1 * ah2 - aw1 * ah2 * dw1
dw1 * aw2 * ah1 + aw1 * ah2 * dw1 == aw1 * ah2
dw1 * (aw2 * ah1 + aw1 * ah2) == aw1 * ah2
dw1 == aw1 * ah2 / (aw2 * ah1 + aw1 * ah2)
    == 400 * 500 / (600 * 300 + 400 * 500)
    == 20 / (18 + 20)
    == 20 / 38
    == 52.63% // which ends up as style="width:53%" which isn't quite right...
4个回答

2
为什么不只设置图像的高度属性值,而不设宽度呢?
所以: <img height="300" src="path/to/image.png" /> 您还可以通过CSS实现同样的效果:设置高度而不是宽度。重新缩放将是成比例的...

如果我设置高度,那么两张图片怎样才能占满整个屏幕宽度呢?我仍然需要手动计算正确的高度,以便两张图片填满整个宽度。 - Dan
这意味着我们必须独立计算每个图像的宽度/高度值。您只能在客户端(JavaScript)或服务器端(例如通过PHP)输出您的画廊HTML标记时执行此操作。你的选择是什么? - pixeline

0
如果您不需要将它们缩放到相同的大小(以显示整个图像),则可以使用CSS的clip属性。

img {

clip: rect(0 300px 300px 0;
position: absolute; /* the problem with using clip is that the element has to be absolutely positioned, which isn't always as awkward as it seems, but any content around it will need to be cleared somehow, perhaps with a top-margin? */

)


我第一次听说“clip”。听起来像是要裁剪我的图像。我希望整个图像都能显示出来,并保持原始的长宽比。 - Dan
它确实会裁剪(或“剪辑”)图像 ;) 是的,我不确定您是否想要对它们进行裁剪,但由于几乎没有人使用剪辑,所以我认为指出它是一个有用的属性。我要警告您,使用CSS /(X)HTML缩放图像会占用浏览器资源,并不一定是展示图像最好的方式。这种方法并不比其他方式更糟糕,只是成本较高。 - David Thomas
同时使用“剪辑”意味着您不必担心原始大小(除非您想检查最小图像的尺寸并将其保持为剪裁尺寸)。而使用CSS / XHTML则需要进行一些复杂的计算,除非您随意选择并坚持特定的尺寸。 - David Thomas

0

设置高度应该可以正常工作。记得你也可以使用相对值,比如百分比。

<img src="myimage.jpg" height="100%" />

1
这有点奏效,但我必须调整或计算正确的高度以使用,使得两个图像的宽度填满容器的整个宽度。 - Dan

-2
<img id="one" class="equal" style="width:50%;"/>
<img id="two" class="equal" style="width:50%;"/>

2
这会使它们等宽,而不是等高。 - Dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接