Day 2 - CSS Grid
CSS Grid is a 2-dimensional layout system. It handles both columns and rows.
1. Defining Columns
Use grid-template-columns to define width of columns.
fr stands for "fraction" of available space.
Code:
/* CSS */
.cols-3 {
display: grid;
grid-template-columns: 100px 100px 100px;
}
.cols-fr {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* Middle col is 2x wider */
}
Output (Fixed 100px):
1
2
3
Output (Flexible 1fr 2fr 1fr):
1fr
2fr
1fr
2. Grid Gap
The gap property sets the space between rows and
columns.
Code:
/* CSS */
.gap-demo {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
Output:
1
2
3
4
3. Spanning Columns & Rows
Items can span multiple tracks using grid-column or
grid-row.
Code:
/* CSS */
.span-grid {
grid-template-columns: repeat(3, 1fr);
}
.span-col-2 {
grid-column: span 2; /* Spans 2 cols */
}
.span-row-2 {
grid-row: span 2; /* Spans 2 rows */
}
Output:
Col Span 2
1
Row Span 2
2
3
4
5
4. Grid Areas (Dashboard Layout)
The most powerful feature of Grid. You can name areas and visualize your layout in CSS!
Code:
/* CSS */
.dashboard {
display: grid;
/* Define Columns: Sidebar | Main | Main */
grid-template-columns: 200px 1fr 1fr;
/* Define Rows: Header | Content | Widgets | Footer */
grid-template-rows: 60px 1fr 100px 60px;
/* Map the Areas - looks like the layout! */
grid-template-areas:
"header header header"
"nav main main"
"nav widget1 widget2"
"footer footer footer";
}
/* Assign items to areas */
.area-header {
grid-area: header;
}
.area-nav {
grid-area: nav;
}
/* ... etc ... */
Output:
Header
Nav
Main Content