Learn the concept
CSS Grid Layout
CSS Grid is a two-dimensional layout system for rows AND columns simultaneously, while Flexbox is one-dimensional (row OR column). Grid excels at page-level layouts and complex grids; Flexbox is better for component-level alignment and distribution within a single axis.
CSS Grid provides two-dimensional layout control:\n\nContainer properties:\n- display: grid\n- grid-template-columns / grid-template-rows — define tracks\n- grid-template-areas — named regions\n- gap — spacing between cells (works for both Grid and Flexbox)\n- auto-fit / auto-fill with minmax() for responsive grids\n- subgrid — allows nested grids to align with parent grid tracks (advanced)\n\nItem properties:\n- grid-column / grid-row — placement and spanning\n- grid-area — named area placement\n\nGrid vs Flexbox:\n| Feature | Grid | Flexbox |\n|---------|------|--------|\n| Dimensions | 2D (rows + columns) | 1D (row OR column) |\n| Layout approach | Container-driven | Content-driven |\n| Best for | Page layouts, dashboards | Navbars, card rows, alignment |\n| Item placement | Explicit row/column | Source order (mainly) |\n\nRule of thumb: Use Grid for layouts, Flexbox for components. They work great together.
/* Basic grid */
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
/* Named areas — dashboard layout */
.dashboard {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-columns: 250px 1fr 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
/* Responsive grid without media queries */
.auto-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
/* Cards auto-wrap, fill available space */
}Where a consistent structure with specific header, sidebar, main content, and footer areas needs to be maintained across different pages.
That dynamically adjusts the number of columns and item sizes based on the available screen space without using traditional media queries.
With multiple widgets that need to be precisely positioned and sized within a larger container, allowing for flexible rearrangement on different devices.
Design a multi-column blog layout using CSS Grid, including a header, main content area, and sidebar that rearranges on smaller screens.
Create a landing page for a product that uses CSS Grid for overall section layout and responsive image/text blocks.
Smashing Magazine uses CSS Grid for its complex, editorial-style layouts, allowing for sophisticated arrangements of articles, images, and advertisements that are highly responsive.
MDN Web Docs often uses CSS Grid for structuring its content pages, providing clear separation between navigation, main content, and related information, adapting well to various screen sizes.