🟦

CSS Grid

CSS Grid is a two-dimensional layout system that allows dividing a page into rows and columns, creating named areas and aligning elements precisely. It's the modern standard for complex layouts.

Examples

  • display: grid; grid-template-columns: 1fr 3fr; — Sidebar + content layout
  • grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); — Auto responsive columns
  • grid-template-areas: 'header header' 'sidebar main' 'footer footer'; — Named areas
  • gap: 2rem; — Uniform spacing between cells
  • grid-column: 1 / 3; — Element spanning 2 columns

FAQ

Does CSS Grid replace Flexbox?

No, they complement each other. Grid is for two-dimensional layouts (full page, dashboards), Flexbox for one-dimensional components (navbar, button row). Often you use Grid for page structure and Flexbox within sections. Both have complete support in modern browsers.

How do I make a responsive 3-column layout with Grid?

Use repeat() with auto-fit or auto-fill: grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));. This creates columns that never go below 300px and adjust automatically. On small screens they stack in 1 column, on large screens they expand to 3 or more depending on available space, without media queries.

What's the difference between grid-template and grid-auto?

grid-template-* defines the explicit grid (rows/columns you declare). grid-auto-* controls the implicit grid (rows/columns Grid creates automatically if you add more elements). Ex: if you define 2 rows but have 10 elements, Grid creates 8 implicit rows. With grid-auto-rows: 150px; you control their height.