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>
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 a max-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.
html,
body {
margin: 0;
}
.container {
width: 90vw;
max-width: 964px;
margin: auto;
background-color: aqua;
display: flex;
flex-wrap: wrap;
gap: 32px;
}
.container div {
background-color: blue;
height: 200px;
width: 300px;
}
@media (max-width: 1071px) {
.container {
max-width: 632px;
}
}
@media (max-width: 702px) {
.container {
max-width: 300px;
}
}
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
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, and simply use justify-content: center
to center them, keeping the defined gap
distance between them. This will of course result in varying left and right "paddings" of the container:
html,
body {
margin: 0;
}
.container {
width: 90vw;
margin: auto;
background-color: aqua;
display: flex;
flex-wrap: wrap;
justify-content: center;
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>