I would probably do it like this:
Seeing as you have specified a fixed width
-value, you could just make each item have a max-width
of 400px - border and margin
. However, for a more dynamic layout, you could just use max-width: 1200px
on box
, so its resizable and responsive.
I prefer to use gap
instead of margin
in flex
-layouts. With this, you can set each items max-width
to 33.33% (for a 3 row layout), minus the 5px gap
and the 1px border
. Also, you don't have to use display: flex
on the items, as they are already children of a flex
-container (unless you plan to have more content inside them).
This would produce this:
.box {
display: flex;
flex-wrap: wrap;
max-width: 1200px;
flex: 1; /* equal items */
gap: 5px;
}
.item {
border: 1px solid #000;
width: 100%;
max-width: calc(33.33% - 6px);
}
<div class="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>
However, this is also achievable by using margin
and a fixed width
. Then you just have to use the items margin
and border
in the max-width
calculation (5px + 5px + 1px + 1px). Keep in mind when using margin
in the layout, its also going to affect the margin
between the container and the items - not just the gap
between the items.
.box {
display: flex;
flex-wrap: wrap;
width: 1200px;
flex: 1; /* equal items */
}
.item {
border: 1px solid #000;
height: 20px;
margin: 5px;
width: 100%;
max-width: calc(33.33% - 12px);
}
<div class="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>