While Flexbox is designed for one-dimensional layouts (a single row OR a single column), CSS Grid Layout is the premier two-dimensional layout engine in web design. CSS Grid gives developers simultaneous control over both columns and rows, unlocking magazine-style layouts, dashboards, and photo galleries without wrapper divs.
Grid Container: The parent element with display: grid.
Grid Lines: The numbered horizontal and vertical dividing lines (1, 2, 3...) that separate tracks.
Fractional Unit (fr): Represents a fraction of the available free space in the grid container.
.grid-container {
display: grid;
/* 3 columns: fixed 250px sidebar, 2 fractions main, 1 fraction ads */
grid-template-columns: 250px 2fr 1fr;
grid-template-rows: auto 1fr auto;
gap: 20px;
}
Using repeat(), auto-fit, and minmax(), you can create a production-grade responsive card grid that automatically rearranges columns based on screen width without writing a single media query:
.card-grid {
display: grid;
/* Cards will never shrink below 280px; will auto-fill row space */
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 24px;
}
CSS Grid allows you to sketch your layout visually in code using ASCII-like named areas:
.dashboard {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: 60px 1fr 50px;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
}
header { grid-area: header; }
sidebar { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }
Question: When should a developer use Flexbox versus CSS Grid?
Answer: Use Flexbox for 1-dimensional content-driven layouts (navbars, button groups, breadcrumbs, tags) where elements flow along a single axis. Use CSS Grid for 2-dimensional layout-first structures (full-page templates, dashboards, photo galleries) requiring simultaneous row and column coordination.
Boost your CSS and front-end development proficiency by exploring these closely connected topics:
Understand margins, borders, padding, content and the universal box-sizing fix.
Master 1D alignment, justify-content, align-items, flex-wrap and responsive flow.
Eliminate styling conflicts and master selector weights from 0,0,0,1 to !important.