Master CSS Grid Layout with Real-World Examples (Beginner to Advanced)
Source: Dev.to
What is CSS Grid?
CSS Grid is one of the most powerful layout systems in modern web development. It allows you to create complex, responsive layouts with minimal code—without relying heavily on Flexbox or external frameworks. In this guide, you’ll learn how to use CSS Grid with real‑world working examples, from basic layouts to advanced responsive designs.
Basic Grid Layout
Example: 2‑Column Layout
HTML
<div class="grid">
<div>Column 1</div>
<div>Column 2</div>
</div>
CSS
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.grid div {
background: lightblue;
padding: 20px;
}
Result: Two equally sized columns with a 10 px gap.
Responsive Grid (Auto Fit)
Example: Card Layout
HTML
<div class="grid">
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
<div class="card">Card 4</div>
</div>
CSS
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
}
.card {
background: rgb(93 192 223);
padding: 20px;
}
Result: Cards automatically wrap and resize, maintaining a minimum width of 200 px.
Dashboard Layout
HTML
<div class="container">
<header>Header</header>
<aside>Sidebar</aside>
<main>Main Content</main>
<footer>Footer</footer>
</div>
CSS
.container {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 200px 1fr;
gap: 10px;
}
header {
grid-area: header;
background: #596af7;
color: white;
}
aside {
grid-area: sidebar;
background: #eee;
color: black;
}
main {
grid-area: main;
background: #eee;
}
footer {
grid-area: footer;
background: #333;
color: white;
}
Result: A classic dashboard with a fixed‑width sidebar and responsive main area.
Image Gallery Layout
HTML
<div class="img-gallery">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
</div>
CSS
.img-gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 10px;
}
.img-gallery img {
width: 100%;
height: 150px;
object-fit: cover;
}
Result: A responsive gallery that fills each row with as many images as will fit at a minimum width of 250 px.
Centering with Grid
HTML
<div class="grid-center">
Grid Center
</div>
CSS
.grid-center {
display: grid;
place-items: center;
height: 100vh;
}
Result: The text “Grid Center” is perfectly centered both vertically and horizontally within the viewport.
CSS Grid vs Flexbox
Both CSS Grid and Flexbox are powerful layout tools, but they excel in different scenarios:
- CSS Grid is ideal for two‑dimensional layouts (rows and columns) such as dashboards, galleries, and complex page structures.
- Flexbox shines for one‑dimensional layouts (either a row or a column), like navigation bars, button groups, or simple alignment tasks.
Choosing the right tool depends on the layout requirements of your project.