I have found a solution that addresses both the image aspect-ratio problem and the fixed-width issue.
To ensure the grid has a fixed width, you can set the width: auto
property so that the floats wrap to multiple lines if needed:
.grid-row {
width: auto;
margin: 0 auto;
}
To make sure the images scale correctly based on their aspect ratio, create two classes:
.table-cell img.portrait {
height: 100%;
}
.table-cell img.landscape {
width: 100%;
}
Then, utilize this jQuery method to apply the correct class depending on each image's aspect ratio:
$('.table-cell').each(function(){
var image = $(this).find('img');
aspectRatio = image.height()/image.width();
if (aspectRatio > 1)
{
image.addClass('portrait');
}
else
{
image.addClass('landscape');
}
});
View Demo Fiddle
Additional Note
You may also explore CSS techniques similar to those discussed in the following question to make the .card
elements responsive while maintaining their aspect ratio:
How do you vertically center absolute positioned text w/o declaring container size and w/o JS?