Issue
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.
Solution
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
Answered By - Antyos
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.