<28/>
28 Lazy Coder
CSS

CSS Grid Layout: A Complete Beginner’s Guide with Examples

Featured Image
CSS Grid Layout tutorial cover image showing a grid structure and code editor on 28LazyCoder
The Article
Table of Contents

Open Instagram’s explore page. Dozens of photos, neatly arranged in perfect rows and columns, all the same size, all lined up without a single gap out of place.

Now open Amazon’s homepage. Product cards arranged in a clean grid — same width, same spacing, automatically adjusting when you resize the browser.

Neither of these was built with guesswork. Both use grid-based layouts — and in CSS, the tool built specifically for this job is called CSS Grid.

If you’ve ever tried to line up cards or images using floats and margins, and ended up fighting with spacing that never quite matched — this guide is going to feel like a huge relief.

Let’s build this up from zero, the way a senior developer would explain it over a cup of chai.

What Is CSS Grid?

CSS Grid is a layout system that lets you arrange elements on a web page into rows and columns, just like a table — but far more flexible and powerful.

Think about a calendar app. Every date sits in its own neat box, aligned perfectly into 7 columns (days of the week) and multiple rows (weeks). That structure — rows and columns forming a grid — is exactly what CSS Grid was built to create.

css

.container {
  display: grid;
}

That one line is all it takes to turn any element into a grid container. Everything else — how many columns, how much space between items, how big each row is — you control from there.

Note: If you’re comfortable with the box model and basic CSS selectors already, CSS Grid will feel like a natural next step. If not, it’s worth getting comfortable with basic CSS positioning first.

Why Do We Need CSS Grid?

Before Grid existed, developers built layouts using floats, inline-block, or tables — all of which were originally designed for something else and repurposed for layout. This led to layouts that were fragile, hard to make responsive, and full of small alignment bugs.

CSS Grid was built specifically to solve two-dimensional layout — controlling rows and columns at the same time, in one place.

Real-world example: Think about a food delivery app’s restaurant listing page. Restaurant cards need to line up in neat rows and columns, resize on different screens, and keep consistent spacing. That’s a textbook CSS Grid use case.

Grid Terminology You Must Know

Before writing any code, let’s get familiar with a few terms — this makes everything ahead much easier to follow.

TermMeaning
Grid ContainerThe parent element with display: grid applied
Grid ItemAny direct child of the grid container
Grid LineThe dividing lines that make up the structure of the grid (both horizontal and vertical)
Grid TrackA single row or column in the grid
Grid CellA single unit — the intersection of one row and one column
Grid GapThe spacing between rows and columns
Grid AreaOne or more cells combined together, forming a named region

Real-world example: Think of a chessboard. The whole board is the grid container. Each square is a grid cell. The lines separating the squares are grid lines. A group of squares combined (like the four center squares) would be a grid area.

How to Create Your First Grid

Let’s build an actual grid, step by step.

html

<div class="container">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <div class="box">5</div>
  <div class="box">6</div>
</div>

css

.container {
  display: grid;
  grid-template-columns: 200px 200px 200px;
}

.box {
  background-color: #FF7A1A;
  color: white;
  padding: 20px;
  text-align: center;
}

Line-by-line explanation:

Output: Six orange boxes arranged neatly into 2 rows and 3 columns, all equally sized.

Real-world use case: This exact pattern — a fixed number of columns, auto-wrapping rows — is how product grids, photo galleries, and dashboard widgets are commonly built.

Defining Rows and Columns

You’re not limited to fixed pixel widths. CSS Grid gives you a special unit called fr (fraction unit) that divides available space proportionally.

css

.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  grid-template-rows: 100px 200px;
}

What’s happening here?

Real-world example: Think of a YouTube video page layout — the main video player takes up more width (like 2fr), while the sidebar with recommended videos takes less (like 1fr). As the browser resizes, both sections shrink or grow proportionally, keeping the same balance.

Tip: You can mix units freely — grid-template-columns: 200px 1fr 1fr gives you one fixed-width column and two flexible ones that share the remaining space equally.

Gaps Between Grid Items

Instead of using margins (which can cause uneven spacing at the edges), Grid gives you a dedicated property for spacing.

css

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

What’s happening here? gap: 20px adds 20px of space between every row and column — but not around the outer edge of the grid. This keeps spacing perfectly even, without the “double margin” problem you’d get using margins on individual items.

You can also control row and column gaps separately:

css

.container {
  row-gap: 20px;
  column-gap: 10px;
}

Real-world use case: This is exactly how Instagram’s photo grid keeps consistent spacing between every image, no matter how many photos are shown.

Placing Items on the Grid

By default, items fill the grid in order — left to right, top to bottom. But you can manually control exactly where an item sits.

css

.featured {
  grid-column: 1 / 3;
  grid-row: 1 / 2;
}

What’s happening here?

Output: This particular item becomes wider than the others, stretching across two columns, while everything else keeps its normal single-cell size.

Real-world example: Think about a news website homepage — the “featured” or “breaking news” story is usually bigger, spanning across multiple columns, while smaller stories sit in single cells around it. That’s exactly this technique in action.

Warning: Grid lines start counting from 1, not 0. This trips up a lot of beginners coming from array indexing in JavaScript or PHP, where counting starts from 0.

Grid Template Areas

This is one of CSS Grid’s most beginner-friendly features — it lets you literally draw your layout using words.

css

.container {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: 80px 1fr 60px;
  grid-template-areas:
    "sidebar header"
    "sidebar content"
    "sidebar footer";
}

.header   { grid-area: header; }
.sidebar  { grid-area: sidebar; }
.content  { grid-area: content; }
.footer   { grid-area: footer; }

What’s happening here?

Real-world example: This is exactly how a typical dashboard layout (like an admin panel or banking app) is structured — a sidebar on the left that stays fixed, with a header, main content, and footer stacked on the right.

Tip: Grid template areas are one of the easiest ways to visually understand your layout just by reading the CSS — no need to mentally calculate row and column numbers.

Aligning Items Inside a Grid

Sometimes items don’t fill their entire cell, and you need to control their position within it.

PropertyApplied ToControls
justify-itemsGrid containerHorizontal alignment of items inside their cells
align-itemsGrid containerVertical alignment of items inside their cells
justify-contentGrid containerHorizontal alignment of the entire grid within the container
align-contentGrid containerVertical alignment of the entire grid within the container
justify-selfIndividual grid itemHorizontal alignment of one specific item
align-selfIndividual grid itemVertical alignment of one specific item

css

.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  align-items: center;
  justify-items: center;
}

What’s happening here? align-items: center vertically centers every item inside its own cell, and justify-items: center horizontally centers them too — useful when your grid items are smaller than their cells and you don’t want them stuck to a corner.

Real-world use case: This is how icon grids (like an app’s settings menu) keep every icon perfectly centered inside its own box, regardless of the icon’s actual size.

Responsive Grids with auto-fit and minmax()

This is where CSS Grid becomes genuinely powerful for real-world responsive design — without writing a single media query.

css

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

What’s happening here?

Output: On a wide desktop screen, you might see 5 columns. Resize the browser down to tablet width, and it automatically drops to 3 columns. On mobile, it drops to 1 — all without writing a single @media rule.

Real-world example: This is precisely how Amazon and Flipkart’s product grids adjust seamlessly between desktop, tablet, and mobile — more products per row on a laptop, fewer on a phone, with zero manual breakpoints needed for the column count itself.

Note: auto-fit and auto-fill behave similarly but differ when there are empty columns left over. auto-fit collapses empty tracks to zero width; auto-fill keeps them, leaving visible gaps. For most product/card grids, auto-fit gives the cleaner result.

CSS Grid vs Flexbox

This is the question every beginner eventually asks: “Do I use Grid or Flexbox?”

If you’ve already gone through our CSS Flexbox guide, you already know Flexbox is great for aligning items in a single direction. Grid takes this further by handling rows and columns together.

CSS GridFlexbox
DimensionTwo-dimensional (rows AND columns)One-dimensional (row OR column)
Best forOverall page layout, card grids, dashboardsNavbars, toolbars, aligning items in a line
Item sizing controlStrong — precise row/column sizingFlexible — content-driven sizing
AlignmentPowerful for 2D grid alignmentPowerful for 1D alignment
When to useWhen you need structure in both directionsWhen you need items to flow and adjust in one direction

Real-world example: A webpage’s overall layout — header, sidebar, main content, footer — is a great fit for Grid. But the navigation bar inside that header, where menu items need to line up neatly in a single row with equal spacing, is a great fit for Flexbox.

Tip: In real projects, you’ll often use both together — Grid for the overall page structure, Flexbox for smaller components inside it, like navbars, buttons, and cards.

Common Mistakes Beginners Make

Best Practices

Real-World Use Cases

Interview Questions on CSS Grid

  1. What is the difference between CSS Grid and Flexbox? Grid is a two-dimensional layout system (rows and columns together), while Flexbox is one-dimensional (a single row or column at a time).
  2. What does the fr unit mean in CSS Grid? It represents a fraction of the available space in the grid container, allowing proportional, flexible sizing instead of fixed widths.
  3. How do you create a responsive grid without media queries? Using grid-template-columns: repeat(auto-fit, minmax(min-size, 1fr)), which automatically adjusts the number of columns based on available space.
  4. What is the difference between justify-items and justify-content in Grid? justify-items aligns items within their individual cells, while justify-content aligns the entire grid within its container.
  5. What is grid-template-areas used for? It lets you define a layout visually using named regions, then assign elements to those regions using grid-area — making complex layouts easier to read and maintain.
  6. Do grid items need to be direct children of the grid container? Yes. Only direct children of an element with display: grid automatically become grid items.

FAQs

Q1. Is CSS Grid supported in all browsers? Yes, CSS Grid has excellent support across all modern browsers, including Chrome, Firefox, Safari, and Edge. It’s safe to use in production projects today.

Q2. Should I learn Flexbox or Grid first? Either order works, but many developers find Flexbox slightly easier to start with since it’s one-dimensional. Once comfortable, Grid builds naturally on those same alignment concepts.

Q3. Can I use CSS Grid and Flexbox together in the same project? Absolutely, and it’s very common. Grid handles the overall page structure, while Flexbox handles alignment within smaller components like navbars and cards.

Q4. What’s the difference between auto-fit and auto-fill? auto-fit collapses empty grid tracks so items stretch to fill available space. auto-fill keeps empty tracks in place, which can leave visible gaps even when there’s fewer items than columns.

Q5. Do I need to specify both rows and columns every time? No. If you only define grid-template-columns, Grid automatically creates rows as needed to fit your content, using a default row height unless you specify grid-auto-rows.

Summary

CSS Grid gives you precise, two-dimensional control over layout — something floats and margins were never really built for. You now understand:

Conclusion

CSS Grid feels a little abstract the first time you read about it — but the moment you build one real layout with it, like a product grid or a dashboard, it clicks fast.

Start small. Take a simple 3-column layout, add a gap, then try grid-template-areas on a basic header-sidebar-content-footer structure. That hands-on practice is what makes Grid feel natural.

External References

AR

Ashutosh Rajbhar

Full-stack developer

3+ years building WordPress, React, and performance-focused web projects.

Related Articles
Previous ← Git vs GitHub: What’s the Difference? (Beginner-Friendly Guide)