HTML/CSS - 14
HTML/CSS - 14: CSS Grid Layout
CSS Grid is a layout system designed for arranging content in rows and columns. It is especially useful when you want several items to line up neatly in a two-dimensional layout.
Like Flexbox, Grid starts on a parent container. You turn an element into a grid container with display: grid;. The elements directly inside it then become grid items.
One of the most important Grid properties is grid-template-columns, which controls how many columns the layout has and how wide they should be.
Your challenge: Arrange six boxes into a grid, then experiment with the number of columns, spacing, and alignment.
What should you notice?
When the container uses display: grid;, the elements inside it can be arranged into rows and columns.
The rule grid-template-columns: repeat(3, 1fr); creates three equal-width columns. Because there are six boxes, the browser automatically creates a second row for the remaining items.
What does 1fr mean? The fr unit means a fraction of the available space. Three columns using 1fr each will share the available width equally.
Experiment: Change repeat(3, 1fr) to repeat(2, 1fr). You should now see two columns and three rows.
Next, try: repeat(4, 1fr). Watch how the browser automatically rearranges the six items into the new grid.
Experiment with gap: Change gap: 15px; to gap: 5px;, then try gap: 30px;. The grid stays the same, but the space between each item changes.
Try uneven columns: Replace the column rule with: grid-template-columns: 2fr 1fr;
Now the first column receives two shares of the available space while the second receives one share, making the first column wider.
Try alignment: Add justify-items: center; to the grid container. You can also try start and end to see how the items move inside their grid cells.
Grid vs. Flexbox: Flexbox is especially useful for arranging items mainly in one direction — a row or a column. Grid is especially useful when you want to control rows and columns together. You will often see both used on the same website.
Good Grid habit: Put the Grid layout rules on the parent container. The elements directly inside that container become the grid items.
👀 Show Solution
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 15px;
}
.grid-item {
background-color: #111;
border: 2px solid #8A8A8A;
padding: 30px;
text-align: center;
border-radius: 6px;
}
</style>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>The .grid-container becomes a grid because it uses display: grid;. The repeat(3, 1fr) rule creates three equal columns, and gap adds space between the grid items.
