I encountered a similar challenge where I needed to display multiple images with varying aspect ratios to occupy the full width of the page or container while ensuring they all have the same height:
https://i.sstatic.net/pc9BF.png
TL;TR
I discovered 2 CSS-only solutions for this issue:
- Utilizing padding and margin properties to maintain a constant aspect ratio of elements
Source:
Set the width of an element as a percentage (e.g., 100%) of the parent's width, then set the element's padding-top (or -bottom) as a percentage to achieve the desired aspect ratio.
- Using flexbox for responsive equal-height images while preserving their aspect ratios
Source: https://codepen.io/blimpage/pen/obWdgp
Assign the flex property of each image's wrapper div to the image's aspect ratio (width divided by height).
Both solutions require prior knowledge of the image sizes to implement suitable CSS adjustments. This can be achieved through server-side scripts like PHP, which offers functions like getimagesize() for such tasks.
Details
Solution 1. A pure CSS approach using the padding attribute with detailed explanations:
- W - page/container width.
- H - block with images width (constant for all).
- w0[i], h0[i] - original size of ith image.
- w[i], h[i] - displayed size of ith image with h[i]=H.
The calculations involve determining ratios, summing up these values, and deriving the aspect ratio for the entire container, among other steps.
An illustrative PHP code example is provided for clarity.
Solution 2. A variant using flexbox that also requires server-side knowledge of image sizes for inline CSS generation:
- W - page/container width.
- H - block with images width (same for all).
- w0[i], h0[i] - original size of ith image.
- w[i], h[i] - displayed size of ith image.
- r[i]=w0[i]/h0[i]=w[i]/h[i] - image's aspect ratio.
- h[i]=H - images should have identical heights.
This solution involves setting the flex property of each image's wrapper div based on the image's aspect ratio to dynamically adjust image widths.
A PHP sample demonstrates how this can be implemented effectively.
Both approaches offer insights into handling equal-height images responsively while maintaining their aspect ratios intact.