Sub topic 3
Placing and Spanning Items Across Columns
Assume you know basic HTML, CSS selectors, units, and the box model. CSS Grid lets you place elements on named rows and columns instead of relying on accidental wrapping.
Placing and spanning items
grid-column sets an item’s starting line and ending line. span sets how many columns it occupies.
<div class="grid">
<main class="main">Main content</main>
<aside class="sidebar">Sidebar</aside>
</div>.grid {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 1.5rem;
}
.main {
grid-column: 1 / span 8;
}
.sidebar {
grid-column: 9 / span 4;
}Both items remain aligned to the same twelve-column structure.
Changing the grid at different screen sizes
Use a media query when a layout needs a deliberate change. On a narrow screen, let each item use the full width.
.grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1rem;
}
.main,
.sidebar {
grid-column: 1 / -1;
}
@media (min-width: 48em) {
.grid {
grid-template-columns: repeat(12, 1fr);
gap: 1.5rem;
}
.main {
grid-column: span 8;
}
.sidebar {
grid-column: span 4;
}
}The breakpoint is a layout decision, not a device label. Choose it where the content stops fitting comfortably.
Card grids with `auto-fit` and `minmax()`
For repeated cards, let the browser choose the number of columns:
.cards {
display: grid;
grid-template-columns: repeat(
auto-fit,
minmax(min(100%, 16rem), 1fr)
);
gap: 1.5rem;
}Each card is at least 16rem when possible. Extra space is shared equally.
Nested grids and `subgrid`
A nested grid normally starts a new column system. subgrid reuses the parent’s tracks and gutters, keeping nested content aligned.
.article {
display: grid;
grid-template-columns: subgrid;
grid-column: 1 / -1;
}
.figure {
grid-column: 1 / span 4;
}
.text {
grid-column: 5 / span 8;
}Check browser support before depending on subgrid for essential layout behavior.
Source order and common pitfalls
Keep HTML order aligned with reading order. Avoid using order or grid placement to make a later element appear before earlier content. Visual order can differ from keyboard and screen-reader order.
Common problems include:
- Fixed item widths causing horizontal overflow.
- Large gaps leaving too little room for readable text.
- Negative line numbers or spans that exceed the grid.
- Different nested grids drifting out of alignment.
- Breakpoints chosen before testing real content.
Exercise
A card grid must show one card per row below 30rem and three equal cards above 30rem. What CSS approach fits?
Show answer
Use a media query with one column below 30rem, then change to repeat(3, 1fr) at min-width: 30rem; use gap for consistent spacing.