CSS Grid Layout

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;
}

Try It Now

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 */
}

Try It Now

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 */
}

Try It Now

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;
}

Try It Now

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;
}

Try It Now

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));
}

Try It Now

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;
}

Try It Now

8. Aligning Items

Use justify-items (horizontal), align-items (vertical), and place-items (both).

.container {
    display: grid;
    justify-items: center;
    align-items: center;
}

Try It Now

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;
}

Try It Now

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.