简体   繁体   English

如何在不知道它们的尺寸的情况下并排在 flexbox 中使图像具有相同的高度

[英]How do I make images the same height in a flexbox side-by-side, without knowing their dimensions

I would want to make 2 images with different widths, displayed the same height side-by-side, ideally in a flex box.我想制作 2 张不同宽度的图像,并排显示相同的高度,最好在一个 flex 框中。

The following works if I know the image dimensions (962x706 and 962x1275).如果我知道图像尺寸(962x706 和 962x1275),则以下内容有效。

Is there a way to do this without knowing their dimensions?有没有办法在不知道它们的尺寸的情况下做到这一点?

<div style="display: flex; margin: 0 -5px">
    <div style="flex: calc(962/706); margin: 0 5px">
        <img src="https://i.stack.imgur.com/H7QKE.jpg"/>
    </div>
    <div style="flex: calc(962/1275); margin: 0 5px">
        <img src="https://i.stack.imgur.com/nsyuX.jpg"/>
    </div>
</div>
img {
  width: 100%;
}

A fiddle for convenience https://jsfiddle.net/b1f6v3kc/为方便起见的小提琴https://jsfiddle.net/b1f6v3kc/

Setting a minimum height with object fit would crop the image, avoiding distortion设置对象适合的最小高度将裁剪图像,避免失真

 img { width: 100%; min-height: 300px; height: 100%; object-fit: cover; }
 <div style="display: flex; margin: 0 -5px"> <div style=" margin: 0 5px"> <img src="https://i.stack.imgur.com/nsyuX.jpg"/> </div> <div style=" margin: 0 5px"> <img src="https://i.stack.imgur.com/H7QKE.jpg"/> </div> </div>

You could set a fixed height for the all the images or use javascript to know the dimensions.您可以为所有图像设置固定高度或使用 javascript 来了解尺寸。 You must take in count that if you modify the height only the aspect ratio change and the image could look bad您必须考虑到,如果您修改高度,则只有纵横比会发生变化,并且图像可能看起来很糟糕

<div style="display: flex; margin: 0 -5px">
    <div style="margin: 0 5px">
        <img src="https://i.stack.imgur.com/nsyuX.jpg"/>
    </div>
    <div style="margin: 0 5px">
        <img src="https://i.stack.imgur.com/H7QKE.jpg"/>
    </div>
</div>

img {
  width: 100%;
  height: 300px;
}

https://jsfiddle.net/xsn07yaw/ https://jsfiddle.net/xsn07yaw/

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

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