On my html/css/js webpage I have a row of 5 pictures such as this:
They have varying aspect ratios. The html looks like this:
<div id="row1">
<img src='img1.jpg'/>
<img src='img2.jpg'/>
<img src='img3.jpg'/>
<img src='img4.jpg'/>
<img src='img5.jpg'/>
</div>
I would like to ensure that they always take up as much horizontal space in their container (here row1) as they can, under the given conditions:
In short, their height must be tweaked so that their combined width will fill up their parent container's width.
I was looking into css flexbox and masonry type library, but I didn't manage to find a successful implementation.
I would rather like a pure CSS solution, but a simple javascript would be nice. My current solution involves calculating the row height in js from the pictures' widths, and updating the style for each. (It is not very scalable, nor reliable, and quite jerky as the js updates the row heights. I expect to have thousands of these rows on the page)
We don't have to do the calculation for every image - the system will do that for us in the sense if we set the row with the images at row height (any height will do) we can get the width. This gives us a width/height ratio.
Then knowing the final width we want the row to be we can calculate the final height.
let row = document.querySelector('#row');
function sizeRow() {
row.style.height = '100px'; // any height will do - we just want to get a proportion
row.style.height = 'calc(var(--requiredWidth) * ' + 100 / row.offsetWidth + ')';
row.style.opacity = 1;
}
window.onload = sizeRow;
window.onresize = sizeRow;
* {
margin: 0;
padding: 0;
}
#row {
--requiredWidth: 100vw;
white-space: nowrap;
display: inline-block;
opacity: 0;
/* just so we dont see a flashing while resizing */
font-size: 0;
/* remove white space between images */
}
#row img {
height: 100%;
display: inline-block;
}
<div id="row">
<img src='https://picsum.photos/id/1015/200/300' />
<img src='https://picsum.photos/id/1016/300/300' />
<img src='https://picsum.photos/id/1018/300/200' />
<img src='https://picsum.photos/id/1019/1000/200' />
<img src='https://picsum.photos/id/1021/200/1000' />
</div>