I’m trying to create a layout where a set of images:
- Are displayed in a single row.
- Maintain their individual aspect ratios (no distortion).
- Have the same height across all images.
- Collectively fill the entire width of the parent container without leaving any gaps or overflowing.
- The height of the images (and the container) should dynamically adjust so that all images can fit horizontally.
I understand that flex-grow or width: auto can be used to control the widths, but the images either end up with different heights (because of their aspect ratios) or don’t collectively fill the parent’s width.
For example:
<div class="container">
<img src="https://placehold.co/300x400">
<img src="https://placehold.co/400x300">
<img src="https://placehold.co/500x300">
</div>
- The container should take 100% of the available horizontal space.
- The img elements should have the same height, and their widths should adjust proportionally to maintain their aspect ratios.
- The height of the images should be determined dynamically, such that all images fit horizontally inside the container.
How can I achieve this layout? I need a pure CSS solution.
What I’ve Tried:
- Using flex-grow and flex-shrink properties, but this causes the images to have varying heights.
- Setting a fixed height for the container, but this doesn’t adapt dynamically.
Any guidance or examples would be greatly appreciated!
2
Answers
Consider using object-fit to achieve this.
In case knowing the aspect-ratio is an option: