Introduction
While Flexbox excels at one-dimensional layouts (a row or a column), CSS Grid Layout is designed for two-dimensional layouts (rows and columns simultaneously). It provides a powerful and flexible system for designing complex page structures, making it a cornerstone of modern web design for creating entire page layouts with ease.
Key Concepts
Grid Container and Grid Items
Similar to Flexbox, CSS Grid involves a grid container (the parent element) and grid items (its direct children).
- To create a grid container, set
display: grid;ordisplay: inline-grid;on the parent element.
Defining Grid Structure
The core of CSS Grid lies in defining your rows and columns:
-
grid-template-columns: Defines the number and width of columns (e.g.,1fr 1fr 1fr,200px auto 1fr). -
grid-template-rows: Defines the number and height of rows (e.g.,100px auto,repeat(3, 1fr)). -
gap(orgrid-gap): Sets the spacing between grid cells, both row and column gaps.
Placing Grid Items
Grid items can be explicitly placed within the grid using:
-
grid-column-start,grid-column-end(shorthand:grid-column) -
grid-row-start,grid-row-end(shorthand:grid-row)
Alternatively, items can be auto-placed, and you can define grid areas using grid-template-areas.
Quick Example
Let's create a simple 3-column layout using CSS Grid:
html<div class="grid-container"> <div class="item">Header</div> <div class="item">Sidebar</div> <div class="item">Main Content</div> <div class="item">Footer</div> </div> css .grid-container { display: grid; grid-template-columns: 1fr 2fr 1fr; /* Three columns: flexible, double flexible, flexible */ grid-template-rows: auto 1fr auto; /* Header, main content, footer */ gap: 20px; /* Space between grid cells */ max-width: 900px; margin: 0 auto; border: 1px solid #ccc; padding: 15px; } .item { background-color: #f0f8ff; border: 1px solid #ddd; padding: 15px; text-align: center; } .grid-container .item:nth-child(1) { /* Header */ grid-column: 1 / -1; /* Spans all columns */ } .grid-container .item:nth-child(2) { /* Sidebar */ grid-column: 1; grid-row: 2; } .grid-container .item:nth-child(3) { /* Main Content */ grid-column: 2 / 4; /* Spans from column 2 to 4 (end) */ grid-row: 2; } .grid-container .item:nth-child(4) { /* Footer */ grid-column: 1 / -1; /* Spans all columns */ } ## Summary CSS Grid is a powerful two-dimensional layout system ideal for structuring entire web pages. By defining `grid-template-columns` and `grid-template-rows` on a container, you establish a robust grid where items can be precisely placed. It's an indispensable tool for complex and responsive web design.