简体   繁体   中英

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.

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:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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