CSS Grid
45 minCSS Grid Layout is the most powerful layout system available in CSS. Unlike Flexbox, which is one-dimensional, Grid is a two-dimensional system, meaning it can handle both columns and rows simultaneously.
With Grid, you define a structure on the parent container using `grid-template-columns` and `grid-template-rows`. You can then place child items into specific cells or areas within that defined grid.
Grid introduces the concept of the `fr` unit (fraction), which represents a fraction of the available space in the grid container. This makes creating fluid, responsive layouts incredibly intuitive.
Grid is perfect for overall page layouts, complex dashboard designs, and image galleries where precise control over both dimensions is required.
Key Concepts
- Two-dimensional layout (Rows & Columns).
- Grid Container and Grid Items.
- The `fr` unit for flexible sizing.
- Grid Lines, Tracks, and Areas.
- `gap` property for gutters.
Learning Objectives
Master
- Defining grid columns and rows
- Placing items in specific grid cells
- Using `repeat()` and `minmax()` functions
- Understanding implicit vs. explicit grids
Develop
- Architecting full-page layouts
- Combining Grid and Flexbox effectively
- Thinking in two dimensions
Tips
- Use Grid for macro layout (page structure) and Flexbox for micro layout (components).
- Use the Firefox or Chrome Grid Inspector to visualize your grid lines.
- Use `grid-template-areas` for readable, semantic layout definitions.
- Start with `display: grid` on the parent.
Common Pitfalls
- Overcomplicating simple layouts (sometimes Flexbox is enough).
- Confusing grid lines (start at 1) with array indices (start at 0).
- Forgetting that grid items can overlap if placed in the same cell.
- Not handling responsive behavior (use media queries to redefine the grid).
Summary
- CSS Grid handles rows and columns simultaneously.
- It offers precise control over 2D layouts.
- The `fr` unit simplifies flexible spacing.
- It is the standard for modern web page layout.
Exercise
Create a 3-column grid layout.
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
gap: 10px;
background-color: #2196F3;
padding: 10px;
}
Exercise Tips
- Try using the fr unit: grid-template-columns: 1fr 2fr 1fr for flexible columns.
- Use repeat() function: grid-template-columns: repeat(3, 1fr) for cleaner code.
- Experiment with grid-template-areas for semantic layout names.
- Add grid items and use grid-column/grid-row to place them in specific cells.