Sub topic 3
CSS Grid: Building Two-Dimensional Layouts
Assume you know basic HTML, CSS selectors, the box model, and units such as px, %, and rem. CSS Grid uses tracks, which are columns or rows, to place items in two dimensions.
Sizing tracks with `minmax()`
minmax(min, max) gives a track a lower and upper size. This prevents a column from becoming too narrow while allowing it to grow.
.cards {
display: grid;
grid-template-columns: repeat(3, minmax(200px, 1fr));
gap: 1rem;
}Each column is at least 200px. The 1fr maximum lets the columns share remaining space. If the container cannot fit three 200-pixel columns, use a responsive pattern instead.
Responsive grids with `auto-fill` and `auto-fit`
auto-fill creates as many tracks as fit, including empty tracks. auto-fit collapses empty tracks, allowing existing items to expand.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.5rem;
}This often avoids a media query. Use a media query when a layout must change for a specific breakpoint, such as moving a sidebar below the main content.
Aligning items and tracks
justify-items and align-items align items inside their cells. justify-content and align-content position the complete grid inside its container.
| Property | Controls |
|---|---|
| `justify-items` | Horizontal alignment inside each cell |
| `align-content` | Vertical position of the whole grid |
Naming grid lines
Names make line-based placement easier to read.
.page {
display: grid;
grid-template-columns: [sidebar-start] 220px [sidebar-end content-start] 1fr [content-end];
}An item can use grid-column: content-start / content-end.
Nested grids and `subgrid`
A nested grid creates an independent layout. subgrid lets a child reuse its parent’s tracks, which helps cards align their headings or buttons.
.card-list {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.card {
display: grid;
grid-template-rows: subgrid;
grid-row: span 3;
}Use subgrid when shared alignment matters. Otherwise, a normal nested grid is simpler.
Grid or Flexbox: choosing the right tool
Use Grid for two-dimensional layouts, such as page regions or card galleries. Use Flexbox for one-dimensional layouts, such as a navigation row. They can be combined: Grid can define the page, while Flexbox aligns content inside each region.
Putting it together: common layout patterns
A dashboard can use named areas for its large regions and a responsive nested Grid for cards. Keep minimum sizes realistic, and test long content because it can affect automatic track sizing.
Exercise
Which tool fits a toolbar whose controls should flow in one row and wrap when needed?
Show answer
Flexbox, because the toolbar is primarily a one-dimensional layout.