I am trying to create a grid-like layout where each column in a row has the same height and contains an image while maintaining its proportions.
Currently, I am using the flex-grow property to adjust the ratio of the images. Although this works, it often results in overly large images which is not ideal for my project.
https://i.stack.imgur.com/EEb0U.png
I want the images to automatically resize to fit within a single row when there is leftover space.
https://i.stack.imgur.com/6OSyl.png
The flex-shrink property functions similarly to flex-grow but distributes negative space based on the set values.
However, there is a downside as items will never shrink below their original content size, preventing columns from resizing beyond the dimensions of the contained images.
To overcome this issue, I have experimented with adjusting the flex-basis property but faced challenges with wrapping and maintaining equal heights.
My desired outcome is as follows:
Consider the following code snippet:
.container {
display: flex;
flex-wrap: wrap;
width: 600px;
}
.img-container {
padding: 5px;
box-sizing: border-box;
flex-basis: auto;
}
.img {
width: 100%;
height: auto;
}
<div class="container">
<div style="flex-grow: 1; flex-shrink: 1;" class="img-container">
<img class="img" src="https://via.placeholder.com/200x200/" alt="">
</div>
<div style="flex-grow: 1; flex-shrink: 1;" class="img-container">
<img class="img" src="https://via.placeholder.com/200x200/" alt="">
</div>
<div style="flex-grow: 2; flex-shrink: 2;" class="img-container">
<img class="img" src="https://via.placeholder.com/400x200/" alt="">
</div>
</div>
The total width sums up to 200+200+400=800px, leaving a negative space of 200px (800-600=200). By applying the flex-shrink values, we allocate parts of this negative space accordingly.
This calculation results in:
- Width reduction for item one: 1/4*200=50
- Width reduction for item two: 1/4*200=50
- Width reduction for item three: 2/4*200=100
Although these calculations ensure correct proportions, achieving this effect proves challenging due to the limitations imposed by the natural widths of the image elements as determined by flex-basis.
If you have any suggestions on how to address this issue, I would greatly appreciate your input.