CSS **Grid Layout** is a powerful system for designing web page layouts in a **two-dimensional grid** (rows and columns).
1. Basic Grid Structure
To use CSS Grid, set the parent container to display: grid;
.
.container { display: grid; }
2. Defining Rows and Columns
Use grid-template-rows
and grid-template-columns
to define the grid structure.
.container { display: grid; grid-template-columns: 200px 200px 200px; /* 3 columns */ grid-template-rows: 100px 100px; /* 2 rows */ }
3. Using fr
for Flexible Columns
The fr
unit allows columns to take up proportional space.
.container { display: grid; grid-template-columns: 1fr 2fr 1fr; /* Second column is twice as wide */ }
4. Adding Gaps Between Grid Items
Use gap
, row-gap
, and column-gap
to add space between grid items.
.container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
5. Placing Items in Specific Grid Areas
Use grid-column
and grid-row
to position items.
.item1 { grid-column: 1 / 3; /* Spans from column 1 to 3 */ grid-row: 1 / 2; }
6. Auto-Fill and Auto-Fit
Use repeat(auto-fill, minmax())
or repeat(auto-fit, minmax())
for responsive grids.
.container { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
7. Grid Template Areas
Define a layout using grid-template-areas
.
.container { display: grid; grid-template-areas: "header header" "sidebar content" "footer footer"; } .header { grid-area: header; } .sidebar { grid-area: sidebar; } .content { grid-area: content; } .footer { grid-area: footer; }
8. Aligning Items
Use justify-items
(horizontal), align-items
(vertical), and place-items
(both).
.container { display: grid; justify-items: center; align-items: center; }
9. Justifying and Aligning the Grid
Use justify-content
(horizontal) and align-content
(vertical) for the grid container.
.container { display: grid; justify-content: center; align-content: center; }
10. CSS Grid vs. Flexbox
Use **Flexbox** for one-dimensional layouts and **Grid** for two-dimensional layouts.
Conclusion
CSS Grid makes layout management **easier and more powerful** than traditional methods.