skip to Main Content

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.

enter image description here

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


  1. Consider using object-fit to achieve this.

    .container img {
     object-fit: cover;
     max-height: 100px;
    }
    <div class="container">
      <img src="https://placehold.co/300x400" />
      <img src="https://placehold.co/400x300" />
      <img src="https://placehold.co/500x300" />
    </div>
    Login or Signup to reply.
  2. In case knowing the aspect-ratio is an option:

    .container {
      display: flex;
      gap: 5px;
    }
    .container img {
      flex: calc(var(--r));
      min-width: 0;
    }
    <div class="container">
      <img src="https://placehold.co/300x400" style="--r: 3/4">
      <img src="https://placehold.co/400x300" style="--r: 4/3">
      <img src="https://placehold.co/500x300" style="--r: 5/3">
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search