DEV Community

Cover image for Master CSS Grid Layout with Real-World Examples (Beginner to Advanced)
bala senthil
bala senthil

Posted on

Master CSS Grid Layout with Real-World Examples (Beginner to Advanced)

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.

1. Basic Grid Layout

Example: 2 Column Layout

HTML Syntax

<div class="grid">
  <div>Column 1</div>
  <div>Column 2</div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.grid div {
  background: lightblue;
  padding: 20px;
}
Enter fullscreen mode Exit fullscreen mode

Output

2. Responsive Grid (Auto Fit)

Example: Card Layout

HTML Syntax

<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>
Enter fullscreen mode Exit fullscreen mode

CSS

.grid {
  display: grid;
   grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
}

.card {
  background: rgb(93 192 223);
  padding: 20px;
}
Enter fullscreen mode Exit fullscreen mode

Output

3. Dashboard Layout

HTML Syntax

<div class="container">
   <header>Header</header>
   <aside>Sidebar</aside>
   <main>Main Content</main>
   <footer>Footer</footer>
</div>
Enter fullscreen mode Exit fullscreen mode

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; }
Enter fullscreen mode Exit fullscreen mode

Output

4. Image Gallery Layout

HTML Syntax

<div class="img-gallery">
   <img src="./images/Bannerimage.png" alt="">
   <img src="./images/Bannerimage.png" alt="">
   <img src="./images/Bannerimage.png" alt="">
   <img src="./images/Bannerimage.png" alt="">
</div>
Enter fullscreen mode Exit fullscreen mode

CSS Syntax

.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;
}
Enter fullscreen mode Exit fullscreen mode

Output:

5. Centering with Grid

HTML Syntax

<div class="grid-center">
   Grid Center
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

.grid-center{
  display: grid;
  place-items: center;
  height: 100vh;
}
Enter fullscreen mode Exit fullscreen mode

Output

CSS Grid vs Flexbox

Top comments (0)