CSS Layout (Flexbox & Grid)

Two modern CSS tools for arranging elements on a page, without old workarounds like floats.

What is it?

Putting elements side by side, centering something both ways, or making boxes evenly sized used to be hard in CSS. Developers bent tools that weren't built for layout, most famously float (meant for wrapping text around an image), and got fragile side effects.

CSS now has two tools designed for layout:

  • Flexbox arranges items in one direction, a row or a column. It's great for nav bars, toolbars, or centering a few items.
  • Grid arranges items in two dimensions, rows and columns at once. It's great for overall page layout, image galleries, or dashboards with defined regions.

Both work the same way. You turn on the layout mode on a container, and its direct children become items arranged by your rules (spacing, alignment, size, order) instead of pixel positions you calculate by hand.

Explain like I'm 10

Flexbox is like arranging books on one shelf: you can spread them out or squeeze them together, one line at a time. Grid is a bookcase with rows and columns, where one book can even span several slots.

Examples

Flexbox: a simple row layout

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

Flex layout lines up the toolbar's children in a row. justify-content spaces them along the main axis, and align-items centers them on the cross axis. No manual positioning needed.

Grid: a two-dimensional layout

.page {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
}

.sidebar { grid-column: 1; grid-row: 2; }
.content { grid-column: 2; grid-row: 2; }

This sets up a fixed-width sidebar column and a flexible content column, plus rows for header, body, and footer. Then it places specific elements into specific cells.

How it works

Setting display: flex or display: grid switches that element's children from normal block-by-block flow to a dedicated layout algorithm.

Flexbox works out how much space each item needs along one axis, then shares out any extra or missing space by your rules. Grid first builds an explicit grid of rows and columns, then places each child into a cell or a span of cells.

Why does it exist?

Older layout tools weren't designed for general page content. Using them meant workarounds (clearing floats, fixed pixel widths, absolute positioning tricks) that broke easily when content changed. Flexbox and Grid were built for layout, so patterns like equal-height columns or centered content can be written directly.

When to use it

Use Flexbox for items in one row or column: a nav bar, a button group, centering one thing inside another. Use Grid when you need rows and columns at once: a page layout, a photo gallery, or anything that must line up in both directions.

When not to use it

Simple inline text flow (a paragraph, a sentence with a link) needs neither; normal document flow handles it. Using Grid for something that's only ever one row or column adds complexity where Flexbox is simpler.

Common mistakes

  • Using float-based layout out of habit for new work instead of Flexbox or Grid.

  • Mixing up Flexbox's one-axis model with Grid's two-axis model, and forcing complex two-dimensional layouts out of Flexbox alone.

  • Forgetting that container properties (like justify-content) go on the container, while item sizing properties (like flex-grow) go on the children.

Practice exercises

  1. Easy:

    Use Flexbox to center three boxes horizontally in a container, with even spacing between them.

  2. Medium:

    Use CSS Grid to build a page layout with a header, a fixed-width sidebar, and a flexible main content area.

  3. Hard:

    Rebuild a float-based layout with Flexbox or Grid, and explain which workarounds you could remove.

Interview questions

What's the core difference between Flexbox and Grid?

Flexbox arranges items along a single axis (a row or a column). Grid arranges items across two axes (rows and columns) at once.

What CSS property turns an element into a flex or grid container?

display: flex for Flexbox, or display: grid for Grid, set on the parent whose children should be arranged.

Why were floats historically used for layout, and what was the problem?

Floats were designed for wrapping text around images, not page layout. Using them for layout needed workarounds like manually clearing floats so containers didn't collapse.

In Flexbox, what are the 'main axis' and 'cross axis', and how do justify-content and align-items relate to them?

The main axis follows flex-direction (row by default); the cross axis is perpendicular to it. justify-content aligns items along the main axis, and align-items along the cross axis.

If you switch `flex-direction` from `row` to `column`, what happens to the meaning of `justify-content` and `align-items`?

The main axis becomes vertical, so justify-content now controls vertical spacing and align-items controls horizontal alignment. They're defined relative to the main and cross axes, not to horizontal and vertical.

What does the shorthand `flex: 1` expand to, and what does each part control?

flex-grow: 1; flex-shrink: 1; flex-basis: 0%. flex-grow lets the item grow into free space, flex-shrink lets it shrink when space is tight, and a flex-basis of 0% treats its starting size as zero, so space is shared purely by the grow ratio.

What's the difference between `align-items` and `align-content` in Flexbox?

align-items aligns items along the cross axis within their line. align-content aligns whole lines along the cross axis when there's extra space and multiple lines (via flex-wrap: wrap). It has no visible effect on a single-line container.

Why might `justify-content: center` appear to do nothing on a flex container?

If the items grow to fill all the space (e.g. flex: 1 on every item), there's no leftover space on the main axis for justify-content to distribute.

What's the difference between the `fr` unit in Grid and using percentages for column widths?

fr shares out the space left after fixed-size tracks (px values or content-sized tracks) are taken. Percentages are always a fraction of the container's full size, so mixing fixed columns and percentages can overflow if they add up to more than 100%.

Given `grid-template-columns: repeat(3, 1fr);` and one item with `grid-column: span 2`, what happens?

That item takes two of the three equal columns in its row. The other items flow into the remaining space, wrapping to new rows as needed through auto-placement.

What does `grid-template-areas` do, and why is it useful?

It lets you name grid regions with a visual, ASCII-like map of strings, then place children into them with grid-area instead of tracking line numbers. The layout becomes much easier to read at a glance.

What's the difference between `justify-content` and `justify-items`/`justify-self` in Grid?

justify-content positions the grid's tracks as a whole within the container (when they don't fill it). justify-items/justify-self align one item within its own cell along the inline (row) axis, regardless of how the tracks are positioned.

How are absolutely positioned children treated inside a flex or grid container?

They're taken out of normal flow. They don't take part in the flex or grid algorithm, get no cell or main-axis space, and are positioned relative to their containing block as usual.

You set `align-items: center` on an outer flex container, but its content still isn't vertically centered — what's a likely cause?

align-items centers within the height the container actually has. If the container is only as tall as its content (no explicit height, and no parent stretching it), there's no extra space to center within.

What is `flex-basis`, and how does it interact with `flex-grow` and `flex-shrink`?

flex-basis sets an item's starting size along the main axis. flex-grow and flex-shrink then share out any extra or missing space (compared to that basis) by each item's factor.

When would you use `flex-shrink: 0` on a flex item?

When the item should keep its natural size even if the container runs out of space, for example so an icon or fixed-width sidebar isn't squeezed by other flexible items.

Given `.item1 { flex: 1 }` and `.item2 { flex: 2 }` inside the same flex container, how is extra space divided between them?

In proportion to the grow factors: item2 gets twice as much of the extra space as item1. With equal starting sizes, item2 ends up about twice as wide (or tall, in a column).

Why does adding `min-width: 0` (or `min-height: 0`) to a flex item sometimes fix an overflow or truncation bug?

Flex items default to min-width: auto, so they won't shrink below their content's min-content size. Long unbroken text or a wide child can then overflow the container even with flex-shrink set. min-width: 0 removes that floor, so the item can shrink and text-overflow/ellipsis and wrapping can work.

What's the difference between the explicit and implicit grid in CSS Grid?

The explicit grid is the tracks you define with grid-template-columns/grid-template-rows. If items land outside it (through auto-placement or line numbers beyond it), the browser creates implicit tracks for them, sized by grid-auto-rows/grid-auto-columns (auto by default).

What does `grid-auto-flow: dense` change about item placement?

By default, auto-placement never goes back: a gap too small for the current item stays empty. dense lets later items fill earlier gaps, packing the grid tighter but possibly showing items out of source order.

When would you use `repeat(auto-fit, minmax(200px, 1fr))` instead of a fixed `repeat(4, 1fr)`?

When the column count should adapt to the space. It creates as many columns of 200px or wider as fit, then stretches them to fill leftover space, giving a responsive grid with no media queries.

In a 900px-wide container with `grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));`, how many columns are created?

Four columns of 225px each. Four 200px tracks fit in 900px (a fifth would need 1000px), and the fr unit stretches them equally to fill the rest.

What does the `order` property do, and what's an important limitation of it?

It changes the visual order of flex or grid items without changing the HTML. The DOM order stays the same, so tab order and screen reader order still follow the markup and may no longer match what's on screen.

What's the difference between `gap` and using margins to space out flex or grid items?

gap adds space only between items, not at the container's outer edges. Margins need overrides like :first-child/:last-child to avoid extra space at the edges; gap needs none.

Why can a flex or grid item respond to `z-index` even without `position: relative` or `position: absolute` set on it?

Flex and grid items honor z-index (and order) for stacking even with position: static. Ordinary block elements ignore z-index unless their position is something other than static.

Why do flex items with different content heights end up the same height inside a row by default?

align-items defaults to stretch, which stretches each item to the container's cross-axis size unless it has an explicit height or an align-self override. You get equal-height columns for free, which float layouts needed hacks for.

What happens to flex items when the container has `flex-wrap: nowrap` (the default) and they don't all fit on one line?

They shrink (by their flex-shrink factor) to fit the one line. If they can't shrink enough, they overflow the container, because wrapping is off.

What problem does CSS Grid's `subgrid` value solve?

A nested grid normally has its own tracks, so its rows and columns don't line up with the parent's. subgrid lets the nested grid use its parent's track sizes, so its content aligns with the outer grid without manually matching sizes.

Why can forcing a two-dimensional layout out of Flexbox alone become awkward?

Flexbox handles one axis at a time. Wrapped items form new lines, but items in different lines don't align with each other the way Grid's rows and columns do. Getting true row/column alignment (a calendar, a dashboard) needs extra wrappers or fixed widths that Grid doesn't.

In Grid, what determines which cell an item lands in if you don't set `grid-column`/`grid-row` on it?

Auto-placement puts it in the next free cell, following grid-auto-flow (row by row by default, or column by column with grid-auto-flow: column). It creates implicit tracks if the defined ones run out.