I am trying to solve a specific layout issue with grid/flex and cannot seem to find a proper answer. I have 8 items that I want to run in a 3 3 2 layout. Grid makes it easy but I want the two items in the last row to be centered vs left aligned.
The attached image is what I am trying to achieve. 3 column, 8 item grid
CodePudding user response:
Use a 6 column grid, not 3, then place your items accordingly.
.box {
border: 1px solid red;
height:50px;
grid-column: span 2;
}
.grid {
display: grid;
grid-template-columns: repeat(6, 1fr);
gap:1em;
}
.box:nth-child(7) {
grid-column: 2 / span 2;
}
.box:nth-child(8) {
grid-column: 4 / span 2;
}
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Flexbox requires setting a width of c.1/3 on the items.
.box {
border: 1px solid red;
height: 50px;
}
.grid {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.box {
flex: 0 0 30%;
}
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>