WebTech1223411 logo WebTech1223411Web tech, read closely
Front-End

CSS Grid vs Flexbox and How to Pick the Right Layout Tool

You start a layout with flexbox, add a wrap, fight the last row that will not line up with the rows above it, and end up with a pile of calc widths and negative margins.

Monitor showing a web page with a colored grid overlay from browser developer tools, next to a sketchbook with wireframe boxes

You start a layout with flexbox, add a wrap, fight the last row that will not line up with the rows above it, and end up with a pile of calc widths and negative margins. The CSS grid vs flexbox question causes that kind of mess on real projects every week, and it is rarely about which tool is better. It is about which one matches the shape of the problem.

I review front-end pull requests for a living, and most layout bugs I see come from using one of them where the other was the natural fit. Here is the rule set I give to new team members, with concrete cases.

The core difference between CSS grid and flexbox

Flexbox lays items out along one axis at a time. You pick a direction, row or column, and the browser distributes space along that line. When items wrap, each new line is its own independent flex line. Items on line two do not know anything about the column widths on line one.

Grid lays items out in two dimensions at once. You define rows and columns on the container, and items snap into cells or span several. Every item in a column shares that column's width, no matter which row it sits in.

That leads to a useful mental test:

  • Content out: the size of the items should decide the layout. That points to flexbox.
  • Layout in: the layout should decide the size of the items. That points to grid.

When flexbox is the right tool

Flexbox shines for components where items sit in a line and their natural widths matter:

  • Navigation bars. Links of different text lengths in a row, with a logo pushed left and a button pushed right using margin-left auto on the last item.
  • Button groups and toolbars. Icons and labels of different widths, spaced with the gap property.
  • Centering one thing. A single item centered in a box with justify-content and align-items set to center.
  • Media objects. An avatar next to a block of text, where the avatar keeps its size and the text takes the rest with flex 1.
  • Tag lists that wrap freely, where nobody expects tags on different lines to align.

The common thread is that you do not care about alignment across lines. If tags on the second line sit in different positions from tags on the first, that is fine.

When CSS grid is the right tool

Grid wins as soon as alignment in two directions matters:

  • Card grids. A product listing where every column should have the same width and the last row should line up with the rows above. The pattern repeat(auto-fill, minmax(240px, 1fr)) gives you a responsive grid with no media queries.
  • Page layouts. Header, sidebar, main content and footer defined with grid-template-areas, which reads almost like a sketch of the page.
  • Forms. Labels in one column and inputs in another, so every input starts at the same horizontal position regardless of label length.
  • Overlapping elements. Placing text over an image by putting both in the same grid cell, without absolute positioning.

CSS grid vs flexbox side by side

QuestionFlexboxGrid
Dimensions controlledOne axis per containerRows and columns together
Wrapped rows align with each otherNoYes
Sizing driven byItem contentContainer template
Gap supportYes, in all current browsersYes
Overlap items without positioningAwkwardEasy, same cell
Children align to parent tracksNoYes, with subgrid

The counter-take: "grid for layout, flexbox for components" is too blunt

You will hear the rule that grid is for page layout and flexbox is for components. It is a decent starting point, but it breaks down quickly in real work.

Many components are two dimensional. A pricing card with a title, a price, a feature list and a button at the bottom is a classic example. With flexbox, the buttons in a row of three cards sit at different heights whenever the feature lists differ in length. People patch that with flex-grow on the list or margin-top auto on the button, which works until the titles wrap to two lines. With grid and subgrid, each card can borrow row tracks from its parent so titles, prices and buttons line up across all three cards. Subgrid has worked in every major browser since late 2023, so there is no reason to avoid it now.

And some page level structures are one dimensional. A simple stacked article with a sticky header is just a column, and flexbox with a column direction or plain block flow is easier to read than a grid template with one track. Pick by the shape, not by whether you are working at page or component level.

Combining them without a fight

The best layouts usually use both. A typical product page in our codebase looks like this:

  1. The page shell uses grid with three named areas for header, main and footer.
  2. The main area holds a card listing built with an auto-fill grid.
  3. Each card uses subgrid for its internal rows so content aligns across cards.
  4. The button row inside each card uses flexbox with gap, because those buttons only need to sit in a line.

When a component needs to change shape depending on the space it is given rather than the viewport, add CSS container queries on the card. Container queries switch between a grid and a flex arrangement cleanly based on the card's own width.

One practical warning: a parent with overflow hidden or certain grid settings can break sticky children in surprising ways. If a sticky sidebar inside your grid stops sticking, our guide on why position sticky stops working walks through the usual causes.

Debugging layout choices faster

Both Chrome and Firefox DevTools show grid and flex overlays. Click the small grid or flex badge next to the element in the Elements panel, and the browser draws track lines, gaps and item boundaries over the page. I ask every reviewer to check the overlay before suggesting a layout change. Most "the grid is broken" bugs turn out to be an implicit track the author did not know was there, or a min-width auto on a flex item that refuses to shrink below its content. Setting min-width 0 on that item fixes a surprising number of overflow issues.

For more on how far plain CSS has come, see what modern CSS can do now that used to need JavaScript.

Frequently asked questions

Is CSS grid better than flexbox?

Neither is better overall. Grid is better when items must align in rows and columns at the same time, and flexbox is better when items sit in a single line and their content should decide their size. Most real layouts use both together.

Can I use grid and flexbox together?

Yes, and you usually should. A grid container can hold flex containers as items, and a flex item can be a grid container. A common pattern is a grid for the page or card listing, with flexbox inside each card for button rows and small inline groups.

Should I use grid or flexbox for a navbar?

Flexbox is usually the simpler choice for a navbar, because links of different lengths sit in one row and margin-left auto pushes items apart easily. Use grid if the navbar has a fixed three part structure, such as logo, centered menu and actions, that must stay aligned.

LV
Lorenzo Vidal

Lorenzo started as a visual designer and moved into CSS after watching too many of his layouts fall apart on phones. He writes about front-end craft, interfaces and accessibility, and still tests everything with the keyboard first.

More posts by Lorenzo

More in Front-End

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto