Skip to content
css questions

CSS · 2 of 10middle~1 min

What is the difference between flexbox and CSS grid?

#layout#flexbox#grid

Flexbox vs CSS Grid

Flexbox - one-dimensional layout

Designed for laying out items in a single row or column.

css
.nav { display: flex; justify-content: space-between; /* main axis */ align-items: center; /* cross axis */ gap: 16px; }
css
/* centering - the classic use case */ .container { display: flex; justify-content: center; align-items: center; }

CSS Grid - two-dimensional layout

Designed for laying out items in rows and columns simultaneously.

css
.layout { display: grid; grid-template-columns: 240px 1fr; grid-template-rows: 60px 1fr 40px; grid-template-areas: 'sidebar header' 'sidebar main' 'sidebar footer'; gap: 16px; } .sidebar { grid-area: sidebar; } .header { grid-area: header; } .main { grid-area: main; }

When to use which

Use caseFlexboxGrid
Navigation barYes-
Centering contentYesYes
Card rowYes-
Page layout-Yes
Complex 2D layouts-Yes
Item alignment in a lineYes-

They work great together

css
/* Grid for page structure */ .page { display: grid; grid-template-columns: 240px 1fr; } /* Flex for items inside a grid cell */ .header { display: flex; justify-content: space-between; }

Rule of thumb: if you're thinking in rows OR columns - use Flexbox. If you're thinking in rows AND columns - use Grid.

updated

did you know it?

related questions