Lesson 4 · Web development foundations
Modern layout: flexbox and grid
Lay out real interfaces with the box model, flexbox and CSS grid.
About 30 minutes
Tab indents. Press Escape, then Tab, to leave the editor.
For most of the web's history, layout meant hacks: tables used for page structure, floats, and pixel-perfect positioning that broke on any screen it wasn't designed for. Today CSS has two layout systems built for the job. Flexbox arranges items along one line, and grid arranges them in rows and columns at once. Underneath both sits the box model, the rule for how big every element actually is. With these three you can build almost any interface you'll see at work, from a navigation bar to a full dashboard.
The box model
Every element is a rectangular box made of four layers, from the inside out:
- content: the text or image itself, sized by
widthandheight; - padding: space inside the border, which takes the element's background;
- border: a line around the padding;
- margin: transparent space outside the border that pushes other elements away.
The catch is what width means. By default (box-sizing: content-box), width sets only the content, and padding and border are added on top. A box with width: 300px, padding: 20px and a 5px border is really 350px wide. That surprises everyone, so almost every modern codebase starts with this reset:
*, *::before, *::after {
box-sizing: border-box;
}
With border-box, width includes padding and border, so width: 300px means 300px on screen. Try both modes and watch the arithmetic.
Lab
The box model
Every element is a box: content, wrapped in padding, then a border, then margin.
box width = 160 + 2×16 + 2×4 = 200px
space taken = 200 + 2×16 = 232px
width sets the content only, so padding and border make the box wider.
.box {
box-sizing: content-box;
width: 160px;
padding: 16px;
border: 4px solid;
margin: 16px;
}One more rule worth knowing: vertical margins between block elements collapse. If one paragraph has margin-bottom: 24px and the next has margin-top: 16px, the gap is 24px, the larger of the two, not 40px. Margins don't collapse inside flex or grid containers, which is one more reason layouts built with them are easier to reason about. Many teams avoid the issue entirely by spacing children with gap.
Flexbox: one direction at a time
Set display: flex on a container and its direct children become flex items, laid out along a main axis. By default that's a row, left to right in English. The other direction is the cross axis.
flex-directionpicks the main axis:roworcolumn.justify-contentdistributes items along the main axis:flex-start,center,space-betweenand so on.align-itemslines them up on the cross axis:stretch(the default),center,flex-start,flex-end.flex-wrap: wraplets items move onto new lines when they run out of room.gapsets the space between items.
On the items themselves, flex: 1 tells an item to grow and take a share of the spare space. A search field that fills the space next to a button is flex: 1 on the input.
Explore the properties, paying attention to how justify-content and align-items swap roles when you switch flex-direction to column.
Lab
Flexbox lab
Flexbox lines items up along a main axis. Change the settings and watch the boxes move.
Main axis runs left to right. Items have different text offsets, so baseline lines up their numbers.
.container {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: stretch;
flex-wrap: nowrap;
gap: 8px;
}Flexbox is the right tool when content runs in one line and its size should drive the layout: navigation bars, toolbars, a row of tags, centering one thing inside another, or a card's icon next to its text.
Grid: rows and columns together
Flexbox thinks in lines; grid thinks in a table of tracks. You define the columns (and optionally rows) on the container, and items fall into the cells.
.cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
The fr unit means "a fraction of the free space", so repeat(3, 1fr) makes three equal columns, and 2fr 1fr makes a main column twice the width of a sidebar. You can mix units: 240px 1fr is a fixed sidebar beside a flexible main area.
The most useful line in all of grid is this one:
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
It says: make as many columns as will fit, each at least 200px wide, and stretch them to share any extra space. Cards then reflow from one column on a phone to four on a wide monitor without a single media query.
Items can also span tracks. grid-column: span 2 makes a featured card two columns wide, and grid-column: 1 / -1 stretches an item across every column, from the first line to the last.
When to use which
The industry rule of thumb: flexbox for components, grid for layouts, though in practice you'll use both on the same page, often nested. A page might use grid for its header, sidebar and main area; grid again for a gallery of cards; and flexbox inside each card to line up an icon, a title and a button.
| You're building | Reach for |
|---|---|
| A nav bar with a logo left and links right | Flexbox |
| Content that should wrap at its own natural widths, like tags | Flexbox with flex-wrap |
| A gallery or dashboard of equal cards | Grid |
| A page shell with header, sidebar, main and footer | Grid |
| Things that must line up in both rows and columns | Grid |
This split also matches how designers work. Design tools such as Figma have an "auto layout" feature that stacks items in a row or column with fixed spacing and padding, which is essentially flexbox, so a design built with it translates almost property for property. Page-level layouts usually arrive as a column grid (for example 12 columns with fixed gutters), which maps directly onto grid-template-columns and gap. Being able to read a design file and name the CSS that builds it is a large part of a front-end developer's day.
Grid also has the shortest centering in CSS: display: grid; place-items: center; on a container centers its child in both directions. You'll see it, and the flexbox version from the quiz above, in almost every codebase.
Build a page layout
Challenge
A header and a card grid
Build a common layout with both systems:
- Make
headera flex container with the logo on the left and the nav on the right, vertically centered. - Make
.cardsa grid with several columns and a gap between the cards. Userepeat()with fixed columns, orauto-fitwithminmax(). No media queries needed.
Widen and narrow the preview to see how your grid responds.
- The header is a flex container
- The logo and nav sit side by side, vertically centered
- The nav is pushed to the right edge of the header
- The cards are in a grid with several columns
- There's a gap between the cards
Recap
- Every element is content, padding, border and margin;
box-sizing: border-boxmakeswidthmean what you expect. - Flexbox lays items out along one axis:
justify-contenton the main axis,align-itemson the cross axis,gapbetween. - Grid defines rows and columns of tracks;
frshares free space andrepeat(auto-fit, minmax(…, 1fr))makes responsive columns without media queries. - Use flexbox for components that flow in a line and grid for layouts that align in two dimensions, nesting them freely.
Finished this lesson?
Mark it complete to track your progress on this device.