Skip to main content
CodeOath
← All posts

HTML & CSS82 min total · 18 parts

CSS Fundamentals: The Box Model, Specificity, Positioning, and Layout

Part 14 of 18 · ~2 min

Flexbox vs. Grid: Choosing the Right Tool

Both retired the old float and table-based layout hacks for good, and both earned a real place on this exact page — because the two problems they were solving were shaped nothing alike.

FlexboxGrid
Axes it controlsJust one — a row, or a column, never both togetherBoth at once — rows and columns, defined as a single structure
Where sizing decisions come fromMostly the content itself; the container only mops up leftover spaceThe container, upfront, before any content is even considered
Where it earned its keep hereThe "you might also like" rail; the sort-and-filter toolbarThe sidebar-plus-grid page shell; the responsive product grid
Nestable inside each other?Yes, freely — a Flex item can hold a Grid, and the reverse works tooSame answer, either direction

An early draft of the rail actually reached for Grid, on the reasoning that it's the newer, more capable tool:

.rail {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 220px;
  overflow-x: auto; /* the scroll works, but it fights Grid's own sizing model the whole way */
}

It technically scrolled, but every adjustment to the rail's spacing needed track-sizing syntax built for defining an entire two-dimensional structure, spent on a strip of cards that never had a second dimension to define. Swapping it for display: flex with gap and flex: 0 0 220px — the version shown two chapters back — replaced several lines of Grid track configuration with three Flexbox properties, because the rail was never a two-axis problem in the first place. The reverse mistake shows up just as often: trying to lay the product grid out with flex-wrap: wrap instead of Grid. It wraps, but nothing forces the second row's cards to line up under the first row's columns — each row sizes its own items independently, so a short description in row one and a long one in row two leave the columns visibly out of alignment, a seam Grid's explicit tracks never allow in the first place.

A dependable rule of thumb, earned by both mistakes above: default to Flexbox for anything that's really just one line of things, and only bring in Grid once there's an actual second axis — rows and columns both — that genuinely needs defining up front.