html - 如何使并排图像等高 (CSS/HTML)?

标签 html css layout image

两张图片,一张是 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...

最佳答案

为什么不简单地设置图像的 HEIGHT 属性值,而不指定宽度?

所以:<img height="300" src="path/to/image.png" />

您也可以通过 CSS 实现此目的,原理相同:您设置的是高度,而不是宽度。重新缩放将成比例...

关于html - 如何使并排图像等高 (CSS/HTML)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1170422/

相关文章:

google-chrome - 仅适用于 Opera、Safari 和 Chrome 的 CSS 样式表

html - 如何完美缩放整个网页,使其兼容所有浏览器?

php - 锂框架 : how to obtain controller name in layout

html - 移动 CSS 未成为目标

css - 如何显示当前页面标题或标签?

html - 强制 div 到下一列

javascript - 按钮在移动设备上的 react 与在桌面上的 react 不一样

database - 在 MVC3 中使用 "dynamic"布局页面

java - 如何将字符串完美居中 Jpanel 中心

javascript - Canvas 变换后,如何获取正在绘制的对象的 2d 尺寸,以便在 Canvas 2d 上进行 HitTest ?