Sub topic 7
Fluid layouts with Flexbox and Grid
A fluid layout adapts to the space it is given. It does not jump between fixed designs. In a mobile-first stylesheet, most of the adapting happens in the base styles. Media queries then handle only the few changes that cannot be expressed fluidly.
This chapter assumes you know the box model, can write a basic Flexbox or Grid rule, and have read the chapters on base styles and min-width queries. You should also be able to inspect an element in your browser's developer tools.
What makes a layout fluid
A layout is fluid when track and item sizes come from ranges and proportions, such as 1fr, minmax(), flex-basis and percentages. Fixed pixel widths do not qualify. The browser then solves the layout for whatever width it has.
This gives you three practical benefits:
- You write fewer media queries, because the layout reflows on its own.
- Widths between your breakpoints still look right.
- Components survive being placed in containers you did not plan for.
Flexbox and Grid solve different problems. Flexbox distributes items along one axis and lets them wrap. Grid defines rows and columns together.
Flexbox: one-dimensional flow
Flexbox is a good fit when the content sets the size: navigation links, tag lists, toolbars, and rows of cards that may wrap.
Wrapping items with flex-basis
The flex shorthand takes three values: flex-grow, flex-shrink and flex-basis. For fluid wrapping, the basis acts as a preferred minimum width. The grow value lets items share leftover space.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flex cards</title>
<style>
body { margin: 0; padding: 1rem; font-family: system-ui, sans-serif; }
.cards-flex {
display: flex;
flex-wrap: wrap;
gap: 1rem;
padding: 0;
list-style: none;
}
.cards-flex > li {
flex: 1 1 16rem;
padding: 1rem;
border: 1px solid #ccd;
border-radius: 0.5rem;
}
</style>
</head>
<body>
<ul class="cards-flex">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</body>
</html>Each item wants 16rem. When the container cannot fit another 16rem item plus the gap, the item wraps to a new line. The items on each line then grow equally to fill it. On a phone you get one column. On a tablet you might get two or three. No media query is involved.
The uneven last row
Flex wrapping has no knowledge of columns. Each line is laid out separately. With five items and three fitting per line, the second line holds two items, and both grow to fill the full width. They end up wider than the items above them.
If you want the last row to line up with the rows above, Flexbox is the wrong tool. Use Grid. Setting flex-grow: 0 stops the stretching, but then each row leaves unused space at its end.
Text overflow in flex items
A flex item has an implicit min-width: auto. It will not shrink below its content's minimum size. A long URL or a wide <pre> block can therefore push the layout past the screen edge. Fix it on the item that overflows:
.cards-flex > li {
min-width: 0;
overflow-wrap: anywhere;
}Grid: two-dimensional layout
Grid works best when columns should line up across rows. It also suits page-level structure.
The auto-fit pattern
This declaration is the most useful fluid rule in Grid:
.cards {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
}It reads from the inside out:
minmax(min(100%, 16rem), 1fr)means each column is at least 16rem wide, or the container's full width if that is smaller. Each column grows to share the free space equally.repeat(auto-fit, ...)creates as many such columns as fit.- Rows are created automatically as items overflow the columns.
The min(100%, 16rem) part prevents a common bug. In a container narrower than 16rem, a plain minmax(16rem, 1fr) forces the column to 16rem, and the grid overflows. Capping the minimum at 100% avoids that.
auto-fit versus auto-fill
The two keywords behave differently when there are fewer items than columns that could fit.
| Keyword | Empty tracks | Visible result with 2 items in a wide container |
|---|---|---|
| `auto-fill` | Kept at their minimum size | Items stay at about 16rem, leaving empty space on the right |
| `auto-fit` | Collapsed to zero width | Items stretch to fill the row |
Choose auto-fit when sparse content should fill the row. Choose auto-fill when you want cards to keep a consistent width regardless of how many there are.
Why fr can overflow
A column of 1fr is really minmax(auto, 1fr). The auto minimum means the track will not shrink below its content's minimum size. A long unbreakable string can make one column wider than the screen. Use minmax(0, 1fr) to allow the column to shrink:
.layout {
display: grid;
gap: 1rem;
grid-template-columns: minmax(0, 1fr);
}This is the Grid counterpart of min-width: 0 on flex items, and it fixes the same kind of overflow.
Combining fluid rules with a media query
Fluid rules do not replace media queries. Use a query when the structure changes, for example when a sidebar appears. Keep the base layout simple and add the structural change at a width where the content needs it:
/* Base: single column */
.layout {
display: grid;
gap: 1rem;
padding: 1rem;
grid-template-columns: minmax(0, 1fr);
}
/* Wider screens: add, don't undo */
@media (min-width: 48em) {
.layout {
grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
padding: 2rem;
}
}The base rule needs no query, and the media query only adds the second column. Inside the main column, the .cards grid reflows by itself. The page therefore needs one breakpoint, not one per card arrangement.
Use em in the query so the breakpoint scales if the user changes their default font size. The 48em here is 768px at the default size.
Choosing between Flexbox and Grid
In practice you will nest them. Grid often defines the page, and Flexbox arranges the contents of each cell, such as a card's header and a row of buttons.
| Need | Better fit |
|---|---|
| Navigation links that wrap | Flexbox |
| Card gallery with aligned columns | Grid |
| Page with header, main, sidebar | Grid |
| Centering one item along an axis | Flexbox |
| Items of varying width on a line | Flexbox |
Common errors
- Fixed widths on items. A rule like
width: 300pxon a flex item or grid child overflows on a 320px screen once padding is added. Useflex-basis,minmax()ormax-width: 100%. - Using
margininstead ofgap. Margins add space at the edges of the container and at the ends of rows.gaponly adds space between items. - Forgetting
flex-wrap. The default isnowrap, so items shrink until they cannot, then overflow. - Overflow from a long word. Check for
min-width: 0andminmax(0, 1fr)before reaching foroverflow: hidden, which hides the symptom. - Undoing styles at larger widths. If a media query has to reset what the base styles did, the base was probably written for the wrong screen size.
Exercise
A gallery uses grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr)). On a 18rem-wide container, the page scrolls sideways. What change fixes it, and why does it work?
Show answer
Replace minmax(20rem, 1fr) with minmax(min(100%, 20rem), 1fr). The column minimum was 20rem, which is wider than the 18rem container. With min(100%, 20rem) the minimum becomes the container width when the container is narrower than 20rem, so the single column fits.
Exercise
A row of five cards uses flex: 1 1 16rem with wrapping. The last row has two cards that are much wider than the cards above. Name two ways to fix this.
Show answer
Switch the container to Grid with repeat(auto-fit, minmax(min(100%, 16rem), 1fr)), or use auto-fill so every row keeps the same column width. Keeping Flexbox and setting flex-grow: 0 also stops the stretching, but it leaves empty space at the end of each row.