CSS Grid Basics: Create Complex Layouts Without the Mess

Md AasimMd Aasim
2 min read

If you’ve ever tried to create a layout with columns and rows using just floats or Flexbox, you know how messy it can get. CSS Grid solves that. It’s built for 2D layouts — meaning you can control both rows and columns at the same time.

Let’s go over the basics and compare it to Flexbox with a simple two-column layout example.


Flexbox vs. Grid: The Quick Difference

  • Flexbox is one-dimensional — either a row or a column.

  • Grid is two-dimensional — rows and columns together.


Basic HTML

We’ll use the same markup for both:

<div class="container">
  <div class="box">Column 1</div>
  <div class="box">Column 2</div>
</div>

Using Flexbox

.container {
  display: flex;
}
.box {
  flex: 1;
  padding: 20px;
  background: #eee;
  margin: 10px;
}

Use this when you just need a row or a column of items. It’s quick and easy.


Using CSS Grid

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}
.box {
  padding: 20px;
  background: #ddd;
}

This gives you two equal-width columns. Want three columns? Just add another 1fr. It’s that simple.


Visual Comparison

Here's a simple visual to show how Flexbox and Grid behave differently:

Flexbox (horizontal layout) [ Column 1 ][ Column 2 ]

Grid (defined structure)

+-----------+-----------+
| Column 1  | Column 2  |
+-----------+-----------+

Flexbox flows items; Grid places them.


A More Complex Grid Example

Want to make one item span two columns?

<div class="container">
  <div class="box">A</div>
  <div class="box">B</div>
  <div class="box span-two">C (full width)</div>
</div>
.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}
.span-two {
  grid-column: 1 / span 2;
}

This layout takes seconds to write with Grid and would require awkward hacks in Flexbox.


When to Use What

Use CaseFlexboxGrid
1D layout (row or column only)
2D layout (rows and columns)
Full-page or card grid layouts
Aligning items in a line

Conclusion

Flexbox is great for 1D layouts, but when you need structure and control over both dimensions, Grid makes life easier. Once you try it, you’ll likely use it for most new layouts.

0
Subscribe to my newsletter

Read articles from Md Aasim directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Md Aasim
Md Aasim