Back to Blog

Mastering CSS Grid Layouts

October 12, 20235 min read
Prashant Yadav - CSS Grid Expert

When CSS Grid Layout was introduced, it revolutionized the way we think about web design. Gone are the days of hacking `float` and `clearfix` to create multi-column layouts. With Grid, we can create complex, responsive 2-dimensional layouts with clean and semantic code.

Why CSS Grid?

Flexbox is fantastic for 1-dimensional layouts (layouts in a row OR a column), but Grid shines when you need to handle both rows and columns simultaneously. It allows you to define explicit grid lines, areas, and gaps.

Basic Syntax

Here is how you can set up a simple 3-column grid:

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

In the example above, `repeat(3, 1fr)` creates three equal-width columns. The `fr` unit represents a fraction of the available space in the grid container.

Grid Areas

One of my favorite features is named grid areas. You can visualize your layout right in your CSS:

.layout {
  display: grid;
  grid-template-areas:
    "header header header"
    "sidebar main main"
    "footer footer footer";
}

This makes media queries incredibly powerful. For mobile, you simply redefine the `grid-template-areas` into a single column stack, and the browser handles the rest.

Conclusion

CSS Grid is a must-have tool in any modern frontend developer's toolkit. It simplifies layout code, improves readability, and offers unprecedented control over design. If you haven't started using it yet, now is the time!


Share this article: