in general this is a quite complex problem that needs to be solved by javascript or with your static template approach.
However, there is a light variant to address this issue, CSS grid with grid-auto-flow: dense
, maybe this is sufficient for your use case.
In your case: Imagine every Card is a grid with 6x10 column/row rasterization. You need to classify your images by telling how much rows and columns every image gets, this can be done with this for example:
grid-row: span 2;
grid-column: span 2;
The dense
algorithm of CSS grid will auto place your images to fill the available space in the most efficient order. What won't be possible: Giving the single images auto available sizes.
You'll find more infos here:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout
https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow