'How to create a flexbox grid with a column span and spacing between elements
I am trying to create a flexbox grid which should look like that 
The basic grid layout is pretty easy to create, but I have a very hard time adding the spacing between the elements. As you can see in the code snippet, the spacing in the second line is not working properly.
#flexContainer {
display: flex;
flex-direction: column;
gap: 16px;
height: 200px;
width: 600px;
}
.rowContainer {
display: flex;
flex-direction: row;
gap: 16px;
}
.thirdElement {
flex-grow: 1;
height: 40px;
background-color: red;
}
.twoThirdsElement {
flex-grow: 2;
height: 40px;
background-color: red;
}
<div id="flexContainer">
<div class="rowContainer">
<div class="thirdElement">
</div>
<div class="thirdElement">
</div>
<div class="thirdElement">
</div>
</div>
<div class="rowContainer">
<div class="twoThirdsElement">
</div>
<div class="thirdElement">
</div>
</div>
</div>
Solution 1:[1]
You not need to <div class="rowContainer">. It fixes only with one flex property for #flexContainer.
#flexContainer {
display: flex;
flex-wrap: wrap;
height: calc(80px + (600px / 20)); /* (600px/20) == 5% of 600px. result = 80px + 5%(600px). it is for a gap between rows that is equal with gap: 5%; for columns.*/
align-content: space-between;
gap: 5%;
width: 600px;
}
.thirdElement {
flex-basis: 30%;
height: 40px;
background-color: red;
}
.twoThirdsElement {
flex-basis: 65%;
height: 40px;
background-color: red;
}
<div id="flexContainer">
<div class="thirdElement">
</div>
<div class="thirdElement">
</div>
<div class="thirdElement">
</div>
<div class="twoThirdsElement">
</div>
<div class="thirdElement">
</div>
</div>
Solution 2:[2]
Use CSS grid
#flexContainer {
display: flex;
flex-direction: column;
gap: 16px;
}
.rowContainer {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 16px;
}
.thirdElement {
height: 40px;
background-color: red;
}
.twoThirdsElement {
grid-column:span 2;
height: 40px;
background-color: red;
}
<div id="flexContainer">
<div class="rowContainer">
<div class="thirdElement">
</div>
<div class="thirdElement">
</div>
<div class="thirdElement">
</div>
</div>
<div class="rowContainer">
<div class="twoThirdsElement">
</div>
<div class="thirdElement">
</div>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arman Ebrahimi |
| Solution 2 | Temani Afif |
