π What is display: grid?
display: grid is the property that transforms an element into aGrid Container. Without this property, none of the CSS Grid features work. It activates the two-dimensional layout system that allows you to control rows, columns, spacing, and alignment with incredible precision.
π How to Use display: grid
Basic Grid Activation
.container {
display: grid;
}Once display: grid is applied, all direct children of the container automatically become grid items.
ποΈ Why Use display: grid?
- Enables 2D layout (rows + columns)
- Makes complex layouts simple and clean
- Reduces dependency on floats, tables, and Flexbox wrappers
- Perfect for responsive designs
- Allows precise alignment and spacing
π display: grid vs display: inline-grid
| Value | Description |
|---|---|
| grid | Creates a block-level grid container |
| inline-grid | Creates an inline-level grid container that flows with text |
Inline Grid Example
.inline-box {
display: inline-grid;
grid-template-columns: repeat(3, 1fr);
}π Adding Structure Using Grid Properties
After using display: grid, you can define rows and columns:
Grid with Rows & Columns
.container {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: 100px auto 80px;
}
π§ Example: Simple Three-Column Layout
3 Column Grid
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
gap: 20px;
}
.item {
background: #e2e8f0;
padding: 20px;
border-radius: 8px;
}π Grid Behavior After display: grid
- Children become grid items
- Grid lines are created automatically
- You can position items precisely using grid lines
- Implicit and explicit tracks are generated
Note
π§ display: grid with Responsive Layouts
Responsive Grid Example
.gallery {
display: grid;
gap: 15px;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}This automatically adjusts the number of columns based on screen width β without media queries.
π§© Common Use Cases
- Website layout: header, sidebar, content, footer
- Image galleries
- Card grids
- Dashboards
- Feature sections
β οΈ Common Mistakes
- Forgetting to add grid-template-columns β results in a single column
- Using display: flex when 2D layout is needed
- Applying grid properties to children instead of the container
Note
π₯ Summary
display: grid is the first and most essential step in creating CSS Grid layouts. It turns a normal block element into a powerful layout engine capable of handling complex, responsive, and modern UI structures with minimal code.
Learn more atMDN Docs π