← Back to Examples

CSS Grid Demo

CSS Grid is perfect for two-dimensional layouts (rows AND columns)!

1. Basic Grid - 3 Equal Columns

1
2
3
4
5
6
.container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 10px;
}

The fr unit means "fraction of available space"

2. Mixed Column Sizes

Fixed 200px
1fr
1fr
grid-template-columns: 200px 1fr 1fr;

First column is fixed, rest share remaining space

3. Using repeat()

1
2
3
4
grid-template-columns: repeat(4, 1fr);
/* Same as: 1fr 1fr 1fr 1fr */

4. Responsive Grid with auto-fit

1
2
3
4
5
6
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

Resize the browser to see items automatically reflow! Minimum 200px, maximum 1fr.

This is the magic formula for responsive grids! No media queries needed.

5. Explicit Row Heights

1
2
3
4
5
6
7
8
9
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 100px 150px 100px;

6. Grid Spanning

Span 2 columns
3
4
Span 2 rows
6
7
Span 2x2
9
10
.span-2-cols { grid-column: span 2; }
.span-2-rows { grid-row: span 2; }
.span-both {
    grid-column: span 2;
    grid-row: span 2;
}

7. Named Grid Areas

Header
Main Content
grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
Visual Layout! The template-areas property lets you "draw" your layout with ASCII art.

8. Practical Example: Image Gallery

.gallery {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    grid-auto-rows: 150px;
    gap: 10px;
}
.wide { grid-column: span 2; }
.tall { grid-row: span 2; }

Key Grid Properties Summary

Property Description
grid-template-columns Define column tracks
grid-template-rows Define row tracks
gap Space between items
grid-column Item column position/span
grid-row Item row position/span
grid-template-areas Name areas for easy placement
repeat() Repeat track definitions
minmax() Set min and max track size
auto-fit / auto-fill Create responsive grids

← Back to Examples