I have this aqua container with 6 divs inside of it. I’m using flex-wrap to wrap the divs when they get too big for the current screen, however I want the first div on the top line to align to the left of the aqua container and the final div on that line to align to the right so even when a div gets pushed to a second line, the full space of the container is taken up and there is no empty space leftover.
I don’t want to use space-between because I want the gap between each div to stay the same (32px).
code:
.container {
width: 90vw;
margin: auto;
background-color: aqua;
display: flex;
flex-wrap: wrap;
gap: 32px;
}
.container div {
background-color: blue;
height: 200px;
width: 300px;
}
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
2
Answers
One possibility is to use flex a shorthand property that combines flex-grow ,flex-shrink and flex-basis. As it is not possible to keep your div width and the gap constant and still fill the container, this what I suggest if your div width is not constant but the gap is to fullfill the whole container
Here’s a possible solution, developing @Paulie_D’s comment further:
It takes the 300px width of the single blocks and the 32px gap as given and not to be changed (that’s what I understood from your question and comments), plus that there should be no "gap" right of the rightmost blocks.
The (centered) container has your 90vw
width
, but also amax-width
of 964px (3 x the width of the blocks plus 2 x the gap)In a media query the
max-width
is changed to 632px (2 blocks and 1 gap), starting at 1071px screen width. The 1071px are calculated as follows: 964 (the max. possible width with 3 blocks) divided by 90 (the 90vw) x 100 (full screen width). Same calculation principle for the 702px media query, where there’s only one block per line.If you want your container (i.e. the aqua background) to stay 90vw wide in all screen widths, you can erase all the
max-width
s and media queries simply usejustify-content: center
. This will of course result in varying left and right "paddings" of the container: