Is there a way to fill a given container with an arbitrary number of square, identically-sized children (as few as five and as many as 50) so that the children:
- fill the container leaving as little vertical and horizontal space as possible; and
- do not overflow the container?
For example, imagine a box of 17 circular avatars that have each been scaled up until any further size increase will cause them to wrap and flow beyond the bottom of the container.
I know that I can use JS to calculate the optimal scale of the children to fill the container, but I feel like either flex
or grid
has this functionality built in.
This is about as close as I have gotten:
.container {
border: 1px solid tomato;
display: flex;
flex-wrap: wrap;
gap: 1vw;
height: 100vh;
justify-content: center;
width: 100vw;
}
.container > div {
background-color: coral;
flex: 0 0 12%;
margin: .5em;
}
.container .div::before {
content: '';
display: block;
padding-top: 100%;
}
<div class="container">
<!-- 32 children -->
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div>
</div>
Apologies if this is a duplicate. I've done my honest best to seek the answer before asking.
[EDIT: adding detail]
Here's the desired result showing a box with a FIXED size and items sized until the container is completely filled. If the box were a different size than this or there were a different number of items inside, the items would scale until they each fit inside without overflowing. The alignment of the two orphans at the end is unimportant, but they must be the same size as the rest of the items.