Grid Architecture
Overview
If Flexbox is a 1-Dimensional string of pearls, CSS Grid is a 2-Dimensional chessboard. CSS Grid is the most powerful layout system in the history of the web. It is specifically designed to handle complex architectural layouts containing BOTH Rows and Columns simultaneously. Unlike Flexbox (where the children dictate how much space they want), CSS Grid operates top-down: the Parent container explicitly defines the blueprint of the grid, and the children simply drop into the predefined slots.
Syntax
/* The Parent Container */
.bento-box {
display: grid;
/* Creates a 3x2 Grid (3 columns, 2 rows) */
/* Columns: 150px, 150px, 150px */
grid-template-columns: 150px 150px 150px;
/* Rows: 100px, 100px */
grid-template-rows: 100px 100px;
/* Exactly like Flexbox, gap provides intelligent gutters! */
gap: 20px;
}
/* The Children (Just normally sit in the HTML) */
.item-1 {
/* No CSS needed! It naturally falls into Row 1, Column 1 */
}
.item-2 {
/* Falls into Row 1, Column 2 */
}Common Pitfalls
- Using CSS Grid when you should use Flexbox. If you just need a row of tags, a navbar, or to center a div, use Flexbox. Grid is massive overkill for 1D micro-layouts. Use Grid for macro-architecture (the scaffolding of the whole page or complex dashboard widgets).
- Forgetting that
gapapplies to both rows and columns in Grid. If you want a vertical gap but no horizontal gap, you must be explicit:column-gap: 0; row-gap: 20px;.
Interview Questions
Flexbox is 'Content-Out' (the children look at their content and push against each other to figure out the layout). CSS Grid is 'Layout-In' (the parent container mathematically defines the rigid matrix of the grid first, and forces the children into it).
Real-World Example
Defining a classic 'Holy Grail' layout skeleton instantly.
.layout {
display: grid;
/*
2 columns. The left is 250px (Sidebar),
the right takes up ALL remaining space (Main Content)
*/
grid-template-columns: 250px 1fr;
min-height: 100vh;
}Check Your Knowledge
Test your understanding of Grid Architecture with these quick questions.