When it comes to creating a simple grid of squares (3x3 at most, filling in top to bottom left to right), I have encountered challenges with both flexbox and grid. The DOM structure required for each method seems incompatible or too complex to support both grids effectively.
Below is my flexbox code:
.wrapper {
display: flex;
width: 400px;
height: 400px;
}
.col {
flex: 1;
display: flex;
flex-direction: column;
padding: 5px;
}
.tile {
margin: 5px;
width: 100%;
flex: 1;
}
The corresponding HTML code creates the desired grid:
<div class="wrapper">
<div class="col">
<div class="tile" style="background: red"></div>
<div class="tile" style="background: green"></div>
<div class="tile" style="background: blue"></div>
</div>
<div class="col">
<div class="tile" style="background: red"></div>
<div class="tile" style="background: green"></div>
<div class="tile" style="background: blue"></div>
</div>
<div class="col">
<div class="tile" style="background: red"></div>
<div class="tile" style="background: green"></div>
<div class="tile" style="background: blue"></div>
</div>
</div>
On the other hand, here is the grid CSS:
.grid {
display: grid;
width: 400px;
height: 400px;
grid-template-columns: repeat( 3, 1fr );
grid-template-rows: repeat( 3, 1fr );
grid-gap: 10px;
}
The respective HTML code renders the grid successfully:
<div class="grid">
<div class="tile" style="background: red"></div>
<div class="tile" style="background: green"></div>
<div class="tile" style="background: blue"></div>
<div class="tile" style="background: red"></div>
<div class="tile" style="background: green"></div>
<div class="tile" style="background: blue"></div>
<div class="tile" style="background: red"></div>
<div class="tile" style="background: green"></div>
<div class="tile" style="background: blue"></div>
</div>
My question is: How can I achieve the same grid layout without using div.col in flexbox, while maintaining a clean and organized grid CSS?
I attempted using flex-wrap: row
to eliminate the need for div.col wrappers. Although this approach allowed the tiles to wrap properly and form a 3x3 grid, specifying a height became necessary, which defeats the purpose of having flexible dimensions for the tiles.