CSS Grid

Create powerful two-dimensional layouts with CSS Grid


CSS Grid

Grid is a two-dimensional layout system - it handles both rows and columns simultaneously.

Enabling Grid

.container {
    display: grid;
    grid-template-columns: 200px 1fr 200px; /* 3 columns */
    grid-template-rows: auto 1fr auto;       /* 3 rows */
    gap: 1rem;
}
CSS

Defining Columns

/* Fixed widths */
grid-template-columns: 200px 400px 200px;

/* Flexible with fr units */
grid-template-columns: 1fr 2fr 1fr; /* Middle column is twice as wide */

/* Repeat function */
grid-template-columns: repeat(3, 1fr);      /* 3 equal columns */
grid-template-columns: repeat(4, 200px);    /* 4 fixed columns */

/* Auto-fill responsive grid */
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
CSS

Placing Items

.item {
    grid-column: 1 / 3;  /* Span from column line 1 to 3 */
    grid-row: 1 / 2;     /* Span from row line 1 to 2 */
}

/* Shorthand: span N columns/rows */
.wide-item {
    grid-column: span 2;
}

.tall-item {
    grid-row: span 3;
}
CSS

Named Grid Areas

.layout {
    display: grid;
    grid-template-areas:
        "header  header  header"
        "sidebar content aside"
        "footer  footer  footer";
    grid-template-columns: 200px 1fr 200px;
    grid-template-rows: auto 1fr auto;
    min-height: 100vh;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.aside   { grid-area: aside; }
.footer  { grid-area: footer; }
CSS

Alignment

.container {
    /* Align all items */
    justify-items: center;  /* Horizontal alignment of items */
    align-items: center;    /* Vertical alignment of items */

    /* Align the grid itself (when grid is smaller than container) */
    justify-content: center;
    align-content: center;
}

/* Align individual items */
.item {
    justify-self: end;
    align-self: start;
}
CSS

Practical Examples

Holy Grail Layout

body {
    display: grid;
    grid-template:
        "header header header" auto
        "nav    main   aside"  1fr
        "footer footer footer" auto
        / 200px 1fr    200px;
    min-height: 100vh;
}
CSS

Responsive Card Grid

.cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1.5rem;
    padding: 2rem;
}
CSS

Dashboard Layout

.dashboard {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: auto;
    gap: 1rem;
}

.stat-card { }                         /* 1 column */
.chart     { grid-column: span 2; }   /* 2 columns wide */
.table     { grid-column: 1 / -1; }   /* Full width */
CSS

Grid vs Flexbox

Feature Flexbox Grid
Dimensions 1D (row OR column) 2D (rows AND columns)
Best for Components, navigation, alignment Page layouts, complex grids
Item placement Source order (mostly) Precise row/column placement
Use when Items should flex based on content You need a defined grid structure