简体   繁体   English

Flexbox 为不同大小的图像保持纵横比

[英]Flexbox maintain aspect ratio for different sized images

After sorting through dozens of Flexbox questions on this website with no luck, I figure it's time to just ask.在对这个网站上的几十个 Flexbox 问题进行整理后,我觉得是时候问了。

I want a row of images where the row stretches the entire width of the window, each image is the same height, and all images maintain their original aspect ratios.我想要一排图像,其中该行延伸窗口的整个宽度,每个图像的高度相同,并且所有图像都保持其原始纵横比。 As an example, I have:例如,我有:

 ul { width: 100%; list-style-type: none; padding: 0; display: flex; align-items: stretch; } li { flex-grow: 1; flex-shrink: 1; flex-basis: 0; } img { max-height: 100%; max-width: 100%; object-fit: contain; }
 <ul> <li> <img src="https://dummyimage.com/1920x1080"/> </li> <li> <img src="https://dummyimage.com/1400x1000"/> </li> <li> <img src="https://dummyimage.com/500"/> </li> </ul>

The question Maintain image aspect ratio when changing height is very similar, but the problem with those answers is that all the images are the same aspect ratio.改变高度时保持图像纵横比的问题非常相似,但这些答案的问题是所有图像的纵横比都相同。

If the ratio is know do it like below.如果知道比率,请执行以下操作。 Note the use of a variable where you define the ratio of each image请注意使用变量来定义每个图像的比例

 ul { list-style-type: none; padding: 0; display: flex; } li { flex-grow: calc(var(--r)); flex-basis: 0; } img { max-width: 100%; }
 <ul> <li style="--r: 1920/1080"> <img src="https://dummyimage.com/1920x1080"/> </li> <li style="--r: 1400/1000"> <img src="https://dummyimage.com/1400x1000"/> </li> <li style="--r: 500/500"> <img src="https://dummyimage.com/500"/> </li> </ul>

I ended up combing @Temani Afif 's and @G-Cyrillus ' approaches to get:我最终梳理了@Temani Afif@G-Cyrillus的方法来获得:

 let smoothImg = function () { const images = document.querySelectorAll("ul li img"); for (image of images) { image.parentElement.style.flexGrow = image.offsetWidth/image.offsetHeight; } }; window.onload = smoothImg; window.onresize = smoothImg;
 ul { list-style-type: none; padding: 0; display: flex; } li { flex-grow: 1; flex-basis: 0; } img { max-width: 100%; }
 <ul> <li> <img src="https://dummyimage.com/1920x1080" /> </li> <li> <img src="https://dummyimage.com/1400x1000" /> </li> <li> <img src="https://dummyimage.com/200x150" /> </li> <li> <img src="https://dummyimage.com/300" /> </li> </ul>

However, I realized that what I am ultimately attempting is complicated and that I was better off just using a library: https://github.com/naturalatlas/image-layout然而,我意识到我最终尝试的东西很复杂,而且我最好只使用一个库: https ://github.com/naturalatlas/image-layout

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

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