CSS Grid is a 2-dimensional layout system for building rows and columns at the same time. It’s perfect for page layouts, dashboards, and responsive card grids.
CSS Grid
1) Grid Container, Tracks & Gap
.grid{
display: grid;
grid-template-columns: 100px 1fr 2fr;
grid-template-rows: auto 120px;
gap: 10px;
}
1
2
3
4
5
6
Tracks are columns and rows. The gap adds gutters.
2) fr Unit & minmax()
.grid{
grid-template-columns: 1fr 2fr minmax(180px, 1fr);
}
1fr
2fr
minmax(180px,1fr)
fr distributes free space; minmax() guards against too small/large tracks.
3) auto-fit vs auto-fill
.cards{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
}
Card 1
Responsive with auto-fit + minmax.
Card 2
Responsive with auto-fit + minmax.
Card 3
Responsive with auto-fit + minmax.
Card 4
Responsive with auto-fit + minmax.
Card 5
Responsive with auto-fit + minmax.
Card 6
Responsive with auto-fit + minmax.
auto-fit collapses empty tracks; auto-fill reserves them. Both are great with minmax().
4) Placing Items & Spanning Tracks
.item-a { grid-column: 1 / 3; } /* span two columns */
.item-b { grid-row: 1 / span 2; } /* span two rows */
1 (1/3)
2 (row span)
3
4
5
6
5) Alignment (justify-* & align-*)
.grid{
justify-items: center; /* x inside cells */
align-items: center; /* y inside cells */
justify-content: center; /* x of the whole grid */
align-content: start; /* y of the whole grid */
}
A
B
C
D
E
F
6) Grid Template Areas
.layout{
display: grid;
grid-template-columns: 160px 1fr 1fr;
grid-template-rows: auto 1fr auto;
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; }
Header
7) Auto Placement & Dense Packing
.grid{
grid-auto-flow: row dense;
grid-auto-rows: 80px;
}
Wide
A
Tall
B
C
D
E
dense back-fills gaps when possible (watch out for source-order surprises).
8) Real-World Pattern: Responsive Card Grid
.cards{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
}
Course 1
Short description for card 1.
Course 2
Short description for card 2.
Course 3
Short description for card 3.
Course 4
Short description for card 4.
Course 5
Short description for card 5.
Course 6
Short description for card 6.
Course 7
Short description for card 7.
Course 8
Short description for card 8.
Quick Notes:
- Use
frto distribute free space; combine withminmax()for resilient tracks. auto-fitcollapses empty columns;auto-fillkeeps the track structure.grid-template-areasmakes page layouts readable and maintainable.- Prefer Grid for 2-D layouts; Flexbox for 1-D alignment stacks.