CSS Grid Layout is a powerful 2D grid layout system designed to align items in both rows and columns simultaneously, creating complex web application layouts without requiring float or positioning hacks.
Grid operates via container declarations and column/row definitions:
.grid-wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal flexible columns */
grid-template-rows: auto;
gap: 1.5rem; /* Row and column spacing */
}
/* Responsive auto-fit columns */
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1.5rem;
}
Core grid concepts:
fr): Represents a fraction of the available free space in the grid container.repeat() Function: Duplicates grid columns or rows (repeat(4, 1fr)).minmax(250px, 1fr): Sets a minimum column width of 250px while allowing columns to expand flexibly to 1fr.gap: Defines gutters between grid rows and columns.flowchart TD
A["Grid Container (display: grid)"] --> B["Columns Axis (grid-template-columns)"]
A --> C["Rows Axis (grid-template-rows)"]
B & C --> D["2D Grid Cells & Area Placement"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Grid Demonstration</title>
<style>
.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 1.5rem;
}
.widget-card {
background-color: #1e293b;
padding: 1.5rem;
border-radius: 8px;
border: 1px solid #334155;
}
.widget-card h3 {
color: #38bdf8;
margin-top: 0;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<h2>Dashboard Grid Layout</h2>
<div class="dashboard-grid">
<div class="widget-card">
<h3>Revenue</h3>
<p>$124,500</p>
</div>
<div class="widget-card">
<h3>Users</h3>
<p>14,250 Active</p>
</div>
<div class="widget-card">
<h3>Conversion</h3>
<p>4.8% Rate</p>
</div>
</div>
</body>
</html>
repeat(auto-fit, minmax(250px, 1fr)) for responsive cards: Automatically reflows grid cards without requiring media queries.gap instead of margin for grid item spacing: Ensures uniform spacing between grid items.Create a CSS class .grid-3 using CSS Grid with grid-template-columns: repeat(3, 1fr); gap: 1rem;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.