Lesson 3 of 12 · 10 min · HTML and CSS
Layout with Flexbox and CSS Grid
What you will learn
- Flexbox: direction, alignment, wrapping, grow and shrink
- CSS Grid: tracks,
frunits,gap, areas andrepeat(auto-fit, minmax()) - Common layouts: navigation bar, centred content, card grid, page layout
- How to choose between Flexbox and Grid
- Fix the typical beginner problems
In simple words
Years ago, people laid out web pages with tricks that were never meant for layout. Today CSS has two proper tools. Flexbox arranges items in a single line, in a row or a column, and shares out the space between them, like friends sitting along a bench. Grid arranges items in rows and columns at once, like a table or a seating chart, where you control both directions.
Words to know
- Flex container: an element with
display: flex, which arranges its children in a line. - Main axis: the direction a flex container lays items out (a row by default).
- Grid track: one row or column of a grid.
- fr unit: a fraction of the free space in a grid.
Flexbox
Turn a parent into a flex container and its children become flex items:
<nav class="bar">
<a class="logo" href="/">Myskillgrid</a>
<a href="/roadmaps/">Roadmaps</a>
<a href="/learn/">Learn</a>
<a class="cta" href="/signup/">Sign up</a>
</nav>
.bar {
display: flex;
align-items: center; /* vertical centring (cross axis) */
gap: 1rem; /* space between items */
padding: 0.75rem 1rem;
}
.logo { margin-right: auto; } /* pushes the others to the right */
The main axis runs in the flex-direction (default row, left to right); the cross axis is perpendicular.
| Property (on the container) | Controls |
|---|---|
flex-direction: row | column | row-reverse |
the main axis |
justify-content: flex-start | center | space-between | space-around | space-evenly | flex-end |
alignment along the main axis |
align-items: stretch | center | flex-start | flex-end | baseline |
alignment along the cross axis |
flex-wrap: nowrap | wrap |
whether items wrap onto new lines |
gap |
spacing between items |
align-content |
spacing between wrapped lines |
| Property (on an item) | Controls |
|---|---|
flex-grow |
how much of the extra space this item takes (0 = none) |
flex-shrink |
how much it shrinks when space is short (1 = may shrink) |
flex-basis |
its starting size before growing or shrinking |
flex: 1 |
shorthand for "grow 1, shrink 1, basis 0": share space equally |
align-self |
overrides align-items for one item |
order |
visual order (careful: it does not change the keyboard or screen-reader order) |
margin-left: auto |
pushes an item (and those after it) away |
Centre anything
.centered { display: flex; justify-content: center; align-items: center; min-height: 100dvh; }
(Or display: grid; place-items: center;.) A classic sidebar layout:
.layout { display: flex; gap: 2rem; }
.sidebar { flex: 0 0 240px; } /* fixed 240px, no grow, no shrink */
.content { flex: 1; min-width: 0; } /* take the rest; min-width: 0 lets long text or code shrink */
A row of cards that wraps:
.cards { display: flex; flex-wrap: wrap; gap: 1rem; }
.card { flex: 1 1 250px; } /* each wants 250px, grows to fill the row, wraps when needed */
CSS Grid
Grid lays out in two dimensions. Define columns and rows on the container; place items automatically or explicitly.
.page {
display: grid;
grid-template-columns: 240px 1fr; /* a fixed sidebar and a flexible content area */
grid-template-rows: auto 1fr auto; /* header, main (fills), footer */
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100dvh;
gap: 1rem;
}
.page > header { grid-area: header; }
.page > aside { grid-area: sidebar; }
.page > main { grid-area: main; }
.page > footer { grid-area: footer; }
Named areas make the layout readable, and changing it for small screens is just a new grid-template-areas in a media query.
Useful pieces:
frdivides the free space:grid-template-columns: 1fr 2frmakes the second column twice as wide.repeat(3, 1fr)makes three equal columns.minmax(200px, 1fr)sets a minimum and a flexible maximum.gap(row and column gaps).grid-column: 1 / -1makes an item span all columns;span 2spans two.place-items,justify-items,align-items,justify-content,align-contentalign items within cells or the grid.
A responsive card grid with no media queries
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.5rem;
}
The browser fits as many columns of at least 240px as will fit and stretches them equally: four columns on a laptop, two on a tablet, one on a phone, automatically. auto-fill keeps empty tracks; auto-fit collapses them so the items stretch.
Subgrid and alignment
grid-template-columns: subgrid lets nested grids share the parent's tracks (cards whose titles, text and buttons line up across a row), and is now available in all major browsers.
Flexbox or Grid?
| Question | Use |
|---|---|
| Items in one line (a navbar, a button group, a toolbar, centring one thing)? | Flexbox |
| Content decides the size and items flow and wrap naturally? | Flexbox |
| A page structure or anything with rows and columns that must line up? | Grid |
| Layout defined first, content placed into it? | Grid |
They combine well: Grid for the page frame, Flexbox inside each component. Do not agonise: either works for many cases.
Other modern layout tools
aspect-ratio: 16 / 9keeps media proportions.position: sticky; top: 0for sticky headers and table headings.- Container queries (
@container (min-width: 400px)) style a component by the size of its container, not the screen, so a card adapts wherever it is placed. - Logical properties (
margin-inline,padding-block,inset) support right-to-left languages such as Urdu without rewriting CSS. min-height: 100dvhfor full-height pages on mobile browsers.object-fit: coverfor images that must fill a box without distortion.
Debugging layout
In the browser's DevTools, the Elements panel marks flex and grid containers with a badge; clicking it overlays the lines, areas and gaps. The most common surprises:
- A flex item will not shrink below its content: set
min-width: 0(oroverflow: hidden). justify-contentdoes nothing because the container is not wider than its items (orflex-direction: columnswapped the axes).align-items: centerdoes nothing because the container has no extra height.- Margins
autoon flex items absorb free space. - Images stretching:
align-items: stretch(the default) or missingobject-fit.
Common mistakes
- Using floats, tables or
position: absolutefor page layout. - Mixing up
justify-contentandalign-items(they flip when the direction changes). - Fixed widths and heights that break on small screens.
- Reordering with
orderso that keyboard focus no longer matches the visual order. - Using margins for gaps instead of
gap. - Making everything Grid or everything Flexbox.
Try it yourself
- Build a navbar with Flexbox: logo on the left, links on the right, vertically centred.
- Build a responsive card grid with
repeat(auto-fit, minmax(240px, 1fr))and no media queries. - Build the header, sidebar, main and footer page layout with
grid-template-areas. - Centre a login box in the middle of the screen.
- Open DevTools and use the flex and grid overlays to find why an item will not shrink.
Check yourself
What is the difference between justify-content and align-items in Flexbox?
justify-content aligns items along the main axis; align-items aligns them along the cross axis.
When would you choose Grid over Flexbox?
For two-dimensional layouts, such as page structure or aligned rows and columns; Flexbox is better for one-dimensional rows or columns of items.
What does grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)) do?
It creates as many equal columns, at least 240px wide, as fit in the container, wrapping to fewer columns on narrow screens.
What does flex: 1 mean?
The item can grow and shrink with a zero basis, so several items with flex: 1 share the available space equally.
Interview questions
How do you centre a div horizontally and vertically?
Make its parent a flex container with justify-content: center; align-items: center; (and a height), or use display: grid; place-items: center;.
What is the difference between auto-fit and auto-fill in Grid?
auto-fill creates as many tracks as fit, keeping empty ones; auto-fit collapses empty tracks so existing items stretch to fill the row.
Why use gap instead of margins between items?
gap adds space only between items, not at the edges, works in both Flexbox and Grid, and avoids margin collapsing and extra rules for first and last items.
Summary
- Flexbox arranges items on one axis with
justify-content,align-items,flex-wrap,gapandflex. - Grid arranges rows and columns with
grid-template-columns,fr,gap, areas andrepeat(auto-fit, minmax()). - Use Grid for page structure and Flexbox inside components; combine them.
- Use DevTools overlays to debug, and avoid floats or absolute positioning for layout.
Going deeper
- MDN: Basic concepts of flexbox: the guide to flex containers and items.
- MDN: Basic concepts of grid layout: tracks, lines and areas.
- web.dev: Learn CSS: Flexbox and Grid: free lessons with interactive examples.
- MDN: Container queries: components that respond to their container.
See how much of this you can explain
A free mock interview asks you new questions on HTML, CSS and how the web works for Frontend Developer and scores every answer, with what to fix.