CSS Grid Layout

Overview

CSS Grid is a powerful two-dimensional layout system that allows you to create complex layouts with rows and columns. It provides unprecedented control over web page layout.

Basic Grid Concepts

Grid Container and Grid Items

.container {
    display: grid;  /* Creates a grid container */
    grid-template-columns: 1fr 1fr 1fr;  /* 3 equal columns */
    grid-template-rows: auto auto;  /* 2 rows */
    gap: 20px;  /* Space between grid items */
}

.item {
    background-color: #f0f0f0;
    padding: 20px;
    border: 1px solid #ccc;
}

Grid Template Areas

.container {
    display: grid;
    grid-template-areas:
        "header header header"
        "sidebar main main"
        "footer footer footer";
    grid-template-columns: 200px 1fr 1fr;
    grid-template-rows: auto 1fr auto;
    gap: 10px;
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }

Responsive Grid

.responsive-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

Grid vs Flexbox

  • Grid: 2D layout (rows and columns)
  • Flexbox: 1D layout (row or column)
  • Use Grid for page layouts
  • Use Flexbox for component layouts