Reputation: 35735
I'm trying to display a bunch of boxes in a container, such that they fill a row then wrap around when they reach the container's maximum width.
I can make the basic layout easily by putting the following styles on the container <div>
:
border: 1px solid black;
display: flex;
flex-wrap: wrap;
max-width: calc(100vw - 500px);
That gets me what I want, but the problem is ... let's say each inner box takes up 300px, and on my screen the container has a width of 800px. I'll get two boxes per row.
However, the flexbox and its border won't stop at 600px. It will keep going to the full 800px, even though there's nothing in the remaining 200px.
I've tried playing with the width and max-width properties, but nothing (eg. fit-content
, max-content
, 100%
) made the container constrain itself to the size of its boxes (ie. 600px).
Is it possible to have a wrapping flexbox where the flexbox's width doesn't extend past the boxes inside of it (when there is leftover space)?
Upvotes: 1
Views: 363
Reputation: 4078
Is it possible to have a wrapping flexbox where the flexbox's width doesn't extend past the boxes inside of it (when there is leftover space)?
Yes, though not in the way envisioned in this question.
A parent of dynamic width containing children with explicit width will result in remainder width.
The standard approach is to divide the remainder width among children, growing them dynamically until enough remainder width exists to fit another child.
Drag the bottom right corner to resize this parent horizontally and get a feel for how this approach attacks the problem.
.parent {
background-color: navy;
display: flex;
flex-wrap: wrap;
gap: 2px;
padding: 2px;
width: 400px;
overflow: scroll;
resize: horizontal;
}
.child {
flex-basis: 150px; /* Desired width */
flex-grow: 1; /* Fill up remaning space at a rate of 1 */
background-color: crimson;
height: 75px;
}
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
There are also many good solutions to this problem using Grid layout.
The approach in dealing with remainder width envisioned in this question appears to be removing it from the parent entirely, which is not possible.
I've tried playing with the width and max-width properties, but nothing (eg. fit-content, max-content, 100%) made the container constrain itself to the size of its boxes (ie. 600px).
In order to calculate how many children can fit at the dynamic width, said width has to be set on the parent, at which point the parent is committed and can't then re-adjust its width. This is the issue with any container and not just Flexbox.
Upvotes: 1