0

I have the following grid of thumbnails (links to other pages) and I'm displaying them using a flexbox.

enter image description here

As you can see on the left since one of the images doesn't have the same aspect ratio, it doesn't fit correctly. I want it to fill that whole available space (essentially scale so it fills it and "crop" the overflow.)

The container css is this

display: flex;
flex-direction: row;
flex-wrap: wrap;

And each element has

flex-basis: 20%;

What css can I add to get the behavior I want?

In case it's relevant I'm actually doing this in React where the elements are loaded dynamically, and the css is actually a CSSProperties object, but on the client side it's just rendered as normal css so I believe any css-based solution will still work. Thanks!

abg
  • 319
  • 4
  • 10
  • 3
    Without seeing the code it's a bit hard to help, I suppose each "thumbnail" is a react component, in this case you can set a fixed width/height and use the css property `object-fit`: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit – NULL SWEΔT Jul 10 '21 at 22:39
  • 2
    As @NULLSWEΔT mentioned it would be better if you provide a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). That's a possible solution as well if you want to understand how it works you should check this out [CSS: 100% width or height while keeping aspect ratio?](https://stackoverflow.com/questions/3751565/css-100-width-or-height-while-keeping-aspect-ratio) – Parco Jul 10 '21 at 22:43
  • You tried object-fit? – Suryansh Singh Jul 11 '21 at 00:10

1 Answers1

1

I think you are looking to stretch the height of any elements that do not fit the aspect ratio that are within the flex container correct?

If I am incorrect, or this does not work for your needs, let me know and I will remove this answer.

You could just add a max-width of 20% or a calculated percentage that does not exceed 1/5th the view width to the flex containers child element. Then add object-fit: fill.

body * {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
} 

.flex-parent {
  display: flex;
  flex-wrap: wrap;
}

.flex-child {
  max-width: 20%;
  object-fit: fill;
}
<div class="flex-parent">
  <img class="flex-child" src="https://picsum.photos/300/200">
  <img class="flex-child" src="https://picsum.photos/200/200">
  <img class="flex-child" src="https://picsum.photos/200/200">
  <img class="flex-child" src="https://picsum.photos/200/200">
  <img class="flex-child" src="https://picsum.photos/200/200">
  <img class="flex-child" src="https://picsum.photos/300/200">
</div>
dale landry
  • 7,831
  • 2
  • 16
  • 28