DEV Community

Cover image for Master CSS Grid: Build Responsive Layouts Easily (With Examples)
bala senthil
bala senthil

Posted on

Master CSS Grid: Build Responsive Layouts Easily (With Examples)

Introduction

CSS Grid is one of the most powerful layout systems in modern web development. It allows you to create complex, responsive web layouts with minimal code compared to older methods like floats or even Flexbox.

In this guide, you’ll learn how to use CSS Grid to structure your web pages efficiently. We’ll cover the basics like rows, columns, and grid areas, and then move into building a real-world responsive layout step by step.

Whether you're a beginner or an experienced developer, mastering CSS Grid will help you design cleaner, faster, and more flexible user interfaces.

1. What is CSS Grid?

CSS Grid is a layout system that divides a page into rows and columns.

Basic Structure

.container{
   display:grid;
}
Enter fullscreen mode Exit fullscreen mode

2. Creating Columns & Rows

Example

.container{
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: auto 200px ;
  gap: 10px;
}
Enter fullscreen mode Exit fullscreen mode

Explanation

1fr = Equal space
gap = space between items

3. Positioning Items in Grid

Examples

.item1{
   grid-column: 1/3;
}

.item2{
   grid-column: 2/3;
}
Enter fullscreen mode Exit fullscreen mode

4. Using Grid Template Areas (Best Practice)

Example

.container{
  display: grid;
  grid-template-areas: 
  "header header"
  "sidebar main"
  "footer footer";
  grid-template-columns: 1fr 3fr;
  gap: 10px;
}

.header{
  grid-area: header;
}

.sidebar{
  grid-area: sidebar;
}

.main{
  grid-area: main;
}

.footer{
  grid-area: footer;
}
Enter fullscreen mode Exit fullscreen mode

5. Build a Real-World Layout

HTML Syntax

<div class="container">
   <header class="header">Header</header>
   <aside class="sidebar">Sidebar</aside>
   <main class="main">Main Content</main>
   <footer class="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: 250px 1fr;
  gap: 10px;
}

.header { grid-area: header; background: #333; color: white; }
.sidebar { grid-area: sidebar; background: #f4f4f4; }
.main { grid-area: main; background: #fff; }
.footer { grid-area: footer; background: #333; color: white; }
Enter fullscreen mode Exit fullscreen mode

Output:

6. Make It Responsive

@media (max-width: 768px) {
  .container {
    grid-template-areas:
      "header"
      "main"
      "sidebar"
      "footer";
    grid-template-columns: 1fr;
  }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Conclusion

CSS Grid makes layout design faster, cleaner, and more powerful. Once you master it, you can build almost any modern UI with minimal code.

Top comments (0)