Building Layouts with CSS Grid
While Flexbox is amazing for 1-dimensional layouts (rows OR columns), CSS Grid is the undisputed king of 2-dimensional layouts (rows AND columns at the same time). 👑
Why Use CSS Grid?
Grid allows you to divide a page into major regions and define the relationship in terms of size, position, and layer. It is perfect for:
- Full page layouts (Header, Sidebar, Main Content, Footer)
- Complex photo galleries
- Responsive card grids
The Basics
You define a grid container using display: grid;. Then, you set up the structure using grid-template-columns and grid-template-rows.
A powerful feature is the fr (fraction) unit, which allows you to easily distribute available space. For example, grid-template-columns: 1fr 2fr; makes the second column twice as wide as the first.
Visualizing the Grid
Writing grid templates mentally can be tricky. A visual Grid Generator allows you to draw out your columns, rows, and gaps visually, and it automatically writes the complex CSS for you.