I'm trying to create a layout that looks like this:
The blue blocks are divs
. It's essentially a 3x3 grid
but with gaps in the 3rd and 4th grid column.
How can I create a gap within CSS grid to achieve this layout? I've tried it with flexbox
, but couldn't achieve the above, so hoping a grid
layout is the answer.
Here's my code:
.container{
border: 1px solid;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 0px 0px;
grid-template-areas:
". . ."
". . .";
}
.item{
border: 1px solid lightgrey;
padding: 10px;
}
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
CSS grid allows you to choose which row and column an element will start in (and indeed, though not needed in your case, how many columns/rows it is to span).
This snippet gives the 3rd and 4th children of the wrapper specific grid positions.
.container {
border: 1px solid;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
grid-gap: 10px;
}
.item {
border: 1px solid lightgrey;
padding: 10px;
}
.item:nth-child(3) {
grid-column: 2;
grid-row: 2;
}
.item:nth-child(4) {
grid-column: 3;
grid-row: 2;
}
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
Note: just for a demo it has also introduced a non-zero grid-gap. The grid-area settings have been removed as not needed if the above method is followed.