Sub topic 9
Responsive Layouts with Grid and Flexbox
This chapter assumes you already know the viewport meta tag, the basic @media syntax, the mobile-first min-width pattern, and fluid units such as rem, %, and clamp(). It also assumes you have used display: grid and display: flex at a basic level. Here you combine those tools so a layout reflows as the viewport changes.
Two layout tools, two jobs
Grid and flexbox solve different problems. Choosing the right one often removes the need for a media query.
| Feature | Grid | Flexbox |
|---|---|---|
| Dimensions | Rows and columns together | One axis at a time |
| Sizing starts from | The container's track definitions | The items' content and `flex-basis` |
| Best for | Page structure, card galleries | Toolbars, nav bars, rows of items |
| Wrapping behavior | Items stay aligned to tracks | Each wrapped line sizes independently |
Grid with media queries
The mobile-first card grid starts with one column. Each breakpoint adds columns.
.cards {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
}
@media (min-width: 40em) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 64em) {
.cards {
grid-template-columns: repeat(3, 1fr);
}
}The base rule has no query, so it applies everywhere. Each min-width rule overrides it only when the viewport is wide enough. Because the later rule has the same specificity and comes later in the source, it wins. If you reorder these rules, the 2-column rule would override the 3-column rule on wide screens.
Grid that adapts without breakpoints
You can often let the grid decide the column count itself.
.cards {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(min(16rem, 100%), 1fr));
}Read this from the inside out:
minmax(16rem, 1fr)means each column is at least16remwide and can grow to share the free space.repeat(auto-fit, ...)creates as many columns as fit in the container.min(16rem, 100%)stops the minimum from exceeding the container on very narrow screens. Without it, a 16rem column overflows a 15rem-wide container.
auto-fit collapses empty tracks, so the remaining items stretch to fill the row. auto-fill keeps the empty tracks, so items keep their size and leave blank space at the end of the row. Use auto-fit for cards that should fill the line, and auto-fill when you want a consistent column width.
The trade-off is control. This grid gives you no direct say over whether you get 3 or 4 columns at a given width. If a design requires exactly 3 columns at a certain size, use explicit breakpoints.
Reflowing page areas
For whole-page layouts, grid-template-areas lets a media query rearrange regions by redefining one property.
.page {
display: grid;
gap: 1rem;
grid-template-columns: minmax(0, 1fr);
grid-template-areas:
"header"
"main"
"aside"
"footer";
}
.page > header { grid-area: header; }
.page > main { grid-area: main; }
.page > aside { grid-area: aside; }
.page > footer { grid-area: footer; }
@media (min-width: 48em) {
.page {
grid-template-columns: minmax(0, 1fr) 16rem;
grid-template-areas:
"header header"
"main aside"
"footer footer";
}
}The HTML source order stays the same at every size. Only the placement changes.
minmax(0, 1fr) is deliberate. A plain 1fr is shorthand for minmax(auto, 1fr), so a column can never shrink below its content's minimum width. A wide <pre> block or a long URL can then push the track past the viewport and cause horizontal scrolling. Setting the minimum to 0 lets the column shrink, and you can then handle overflow on the content with overflow-x: auto.
Flexbox that wraps
Flexbox is one-dimensional, but flex-wrap lets it spill onto new lines when items run out of room.
.features {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.features > * {
flex: 1 1 14rem;
}The shorthand flex: 1 1 14rem means flex-grow: 1, flex-shrink: 1, and flex-basis: 14rem. The basis is the ideal width. When a line cannot fit another 14rem item plus the gap, the item wraps. Items on each line then grow to share the leftover space. No media query is involved.
Here is the main difference from grid. Flex lines are sized independently, so a last row with one item stretches across the whole width, while grid keeps that item in its column. If you want a tidy last row, use grid or set a max-width on the items.
Media queries still help with flexbox when you need to change direction, not just wrapping:
.toolbar {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
@media (min-width: 40em) {
.toolbar {
flex-direction: row;
justify-content: space-between;
align-items: center;
}
}On small screens the toolbar stacks its items. From 40em upward it becomes a single row with the items spread across it.
Choosing a technique
A reasonable default order is to try intrinsic sizing first (auto-fit, flex-wrap). Add a media query only when the design needs a structural change that the content cannot produce on its own.
Common errors
- Missing viewport meta tag. On a phone, the layout width is then about 980px, so your
min-widthrules never fire as you expect. Check the tag first when a breakpoint seems to be ignored. - Rules in the wrong order. With mobile-first
min-widthqueries, put smaller breakpoints before larger ones. Equal specificity means the later rule wins. - Overflow from
1fr. As described above, useminmax(0, 1fr)when content such as code or tables must not widen the track. - Fixed heights. A
heighton a card or container clips text when columns get narrower and the text wraps more. Prefermin-heightor let the content decide. - Pixel-based layouts mixed with
remtext. If a user raises their default font size,em-based breakpoints respond to it, andpxbreakpoints do not. Useemconsistently in queries.
Putting it together
A typical responsive page uses several of these techniques at once. A grid-template-areas page frame changes at one breakpoint. Inside main, an auto-fit grid arranges the cards. In the header, a flex toolbar changes direction at a second breakpoint. Each technique handles the part of the layout it is best at, and the media queries are kept to the few places where the structure itself changes.
Exercise
A card grid uses grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)). On a 12rem-wide phone container, the cards overflow horizontally. What change fixes this, and why does it work?
Show answer
Replace 16rem with min(16rem, 100%), giving minmax(min(16rem, 100%), 1fr). The min() function caps the column minimum at the container's width, so when the container is narrower than 16rem the single column shrinks to fit instead of forcing a 16rem track.
Exercise
You build a page frame with grid-template-columns: 1fr 16rem, and a long unbroken URL in the main column causes horizontal scrolling. What is the cause and the fix?
Show answer
A plain 1fr has an automatic minimum equal to the content's minimum width, so the track cannot shrink below the URL's width. Use minmax(0, 1fr) so the track can shrink, and add overflow-wrap: anywhere (or overflow-x: auto for code blocks) on the content.