Basics of Grid Display
The display: grid;
value in CSS enables the Grid Layout, a two-dimensional layout system that offers a more robust and controlled way to handle both rows and columns in your design.
Basic Concepts
- Grid Container: The element on which you apply
display: grid;
becomes the grid container. - Grid Items: The immediate children of the grid container are grid items.
- Grid Lines: The dividing lines that make up the structure of the grid.
- Grid Tracks: The space between two adjacent grid lines, either horizontally (columns) or vertically (rows).
- Grid Cells: A single unit of the grid, defined by the intersection of a grid row and a grid column.
- Grid Areas: A rectangular area between four grid lines, which can contain one or more grid cells.
Syntax
To define a grid container:
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* Three equal columns */
grid-template-rows: 100px 200px; /* Two rows of different heights */
}
Key Properties
On the Grid Container
grid-template-columns
andgrid-template-rows
: Define the size of the columns and rows.grid-gap
: Defines the gap between grid items.grid-template-areas
: Defines named grid areas.
On the Grid Items
grid-column
andgrid-row
: Specify where an item should be placed.grid-area
: Assigns an item to a named grid area.
Examples
Basic 3x2 Grid
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 1fr);
}
Named Areas
.container {
grid-template-areas:
"header header header"
"sidebar content content"
"footer footer footer";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.footer { grid-area: footer; }
Best Practices
- Semantic Structure: Use Grid to enhance the semantic structure of your HTML, not to break it.
- Fallbacks: Provide fallback layouts for browsers that don't support CSS Grid.
- Responsive Design: Use media queries in conjunction with Grid layout to create fully responsive designs.
- Debugging: Modern browsers have excellent dev tools for debugging Grid layouts.
Browser Support
CSS Grid is well-supported in modern browsers, but it's always a good idea to check compatibility if you need to support older versions.