Programming & Web Development

Flexbox vs Grid: Which CSS Layout to Use, With Code Examples (2026)

Flexbox vs grid explained for beginners: what one-dimensional and two-dimensional layout really means, the same card row built both ways, 2026 browser support for subgrid and grid-lanes masonry, common myths, and which one to learn first for web development work in Pakistan.

Flexbox vs grid featured graphic showing a flexible row of items above a two-dimensional grid of cards

Quick answer

Use flexbox when items sit in one row or one column and their content should decide their size, such as headers, buttons and tags. Use grid when rows and columns must line up together, such as page frames and product galleries. Most real pages combine both, and both work in over 97% of browsers.

Key takeaways

  • • Flexbox controls one axis at a time; grid controls rows and columns together.
  • • If you keep switching off flex growth to line items up, switch to grid.
  • • repeat(auto-fit, minmax(240px, 1fr)) keeps the last row of cards the same width as the rest.
  • • Flexbox and grid each show about 97.6% global support on Can I Use; subgrid shows 94.68%.
  • • Masonry with display: grid-lanes works in Safari 26.4+, so keep a plain grid fallback.
  • • Learn flexbox first, then grid the same week, and build one real page that uses both.
Table of contents 14 sections
  1. Flexbox vs Grid at a Glance
  2. What Does One Dimension vs Two Dimensions Mean?
  3. Content Out or Layout In: The Deeper Difference
  4. Where Does Flexbox Fit Best?
  5. Where Does Grid Fit Best?
  6. A Quick Way to Decide for Any Section
  7. The Same Card Row, Built Both Ways
  8. Using Flexbox and Grid Together on One Page
  9. Subgrid for Cards That Must Match
  10. Browser Support in 2026: Is Anything Still Risky?
  11. Myths That Confuse Beginners
  12. Which Should You Learn First for Jobs and Freelancing in Pakistan?
  13. Practicing Layouts in PSTA's Full-Stack Course
  14. Rebuild One Section of a Site You Use Daily

Try this flexbox vs grid self-test before you read on. Picture a website header with a logo on the left and four menu links on the right. Now picture a shop page with 12 product cards in tidy rows and columns. If you would reach for the same CSS tool for both, you are probably spending too long fixing margins.

The short version: flexbox lines items up along one axis, a row or a column. Grid controls rows and columns at the same time. Most real pages use both, and knowing where each one belongs is a skill clients and employers notice quickly.

Here's what this CSS grid vs flexbox comparison covers:

  • The one question that settles most layout decisions
  • Where flexbox is the better fit, and where grid is
  • The same card row built both ways, with the code
  • Browser support in 2026, including subgrid and the new grid-lanes masonry layout
  • Which one to learn first if you want web development work in Pakistan

Flexbox vs Grid at a Glance

Use this table as a quick reference while you code. The support figures come from Can I Use, which showed StatCounter data for October 2026 when we checked it.

Question Flexbox Grid
Direction One axis at a time: a row or a column Rows and columns together
Who decides size Mostly the items and their content Mostly the tracks you set on the container
Wrapping Each wrapped line sizes itself Items stay on shared column tracks
Overlapping items Awkward Simple: place two items in the same cell
Typical jobs Navbars, button groups, centering, tags, card internals Page shells, product galleries, dashboards, aligned forms
Key properties flex-direction, justify-content, align-items, flex-wrap, flex grid-template-columns, grid-template-areas, fr, minmax(), auto-fit
Global browser support 97.57% 97.56%

Support is no longer a reason to pick one over the other. Both work in every browser your visitors are likely to use.

What Does One Dimension vs Two Dimensions Mean?

MDN states the difference plainly in its guide on how grid relates to other layout methods: flexbox was built for one dimension, and grid was built for two.

In practice, one dimension means you care about a single line of items. A menu bar is a row. A sidebar list is a column. If the menu wraps onto a second line, flexbox treats that second line as a fresh row. It does not try to line its items up with the row above.

Two dimensions means the rows and columns must agree with each other. On a results table or a product gallery, the third card in row two should sit exactly under the third card in row one. Grid gives you that alignment because every item sits on the same set of column tracks.

MDN suggests two questions you can ask about any part of a page:

  1. Do I only need to control this by row or by column? Use flexbox.
  2. Do I need to control it by row and column together? Use grid.

Content Out or Layout In: The Deeper Difference

The second way to think about it is who is in charge. MDN describes flexbox as working "from the content out" and grid as working from the layout in.

With flexbox, you hand the browser a group of items and let their content push them into place. A long menu label takes more room, and a short one takes less. That's ideal when you don't know the content in advance, such as tags on a blog post or buttons translated into Urdu and English.

With grid, you draw the structure first. You decide there will be a 260px sidebar and a flexible main area, or four equal columns, and then you drop items into that plan. The content fits the layout rather than the other way around.

This also explains where you write most of your CSS. MDN's flexbox guide notes that grid sizing lives mostly on the container, while flexbox sizing happens on the items themselves.

Where Does Flexbox Fit Best?

Knowing when to use flexbox comes down to this: reach for it when items sit in a single line and their content should decide how much room they take. Common cases from student and client projects:

  • Site headers: logo on one side, menu on the other, everything centered vertically.
  • Button groups: "Add to Cart" and "Buy Now" side by side, stacking on narrow phones.
  • Tags and filters: chips that wrap onto new lines as space runs out.
  • Inside a card: image, title, price and a button pinned to the bottom.
  • Centering one thing: a login box in the middle of the screen.

Here is a header for a local restaurant site in Abbottabad, used as an example:

.site-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

Three lines do the work that once took floats and clearfix hacks. The gap property adds even space between items. According to MDN's gap reference, it works in flex, grid and multi-column containers and has been available across browsers since October 2017.

Where Does Grid Fit Best?

The rule for when to use CSS grid is the mirror image. Use it when you need things lined up in both directions, or when you want the layout to stay fixed whatever the content does. Typical jobs:

  • Page shells: header, sidebar, main area and footer.
  • Product galleries: cards that form clean columns on any screen width.
  • Dashboards: panels of different sizes that span several rows or columns.
  • Forms: labels in one column and fields in another, all starting at the same edge.
  • Overlaps: text placed on top of a banner image without absolute positioning.

A page shell with named areas reads almost like a sketch on paper:

.page {
  display: grid;
  grid-template-columns: 260px 1fr;
  grid-template-areas:
    "header  header"
    "sidebar main"
    "footer  footer";
  gap: 24px;
}
@media (max-width: 768px) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas: "header" "main" "sidebar" "footer";
  }
}

On a phone, the sidebar drops below the main content by changing four lines. The HTML stays untouched, which keeps your markup clean for SEO and screen readers. If you're still getting comfortable with page structure, our cheat sheet of basic HTML tags pairs well with this section.

A Quick Way to Decide for Any Section

When the flexbox vs grid choice isn't obvious, run the section through the flowchart below. One sign from MDN is worth remembering. If you use flexbox and keep switching off its flexibility to make things line up, you probably need grid.

Flexbox vs grid decision tree with two questions for choosing a CSS layout
Two questions settle most layout choices for a single page section.

Apply it to each part of a page separately, not to the whole site at once. A single page often ends up with grid for the outer frame and flexbox inside several components.

The Same Card Row, Built Both Ways

Here's the problem most beginners hit first. You have five product cards and want three per row on a laptop. With flexbox and wrapping, it looks like this:

.products {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.products .card {
  flex: 1 1 240px;
}

The first row holds three cards. The second row holds two, and because each wrapped line sizes itself, those two cards stretch wider than the three above. Prices and buttons no longer line up, and the page looks unfinished.

Grid fixes it with one line on the container:

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

Every card now sits on the same column tracks. The browser fits as many 240px-or-wider columns as the screen allows, and the last row keeps the same card width as the rows above. No media query is needed for this part.

Before and after: five cards with flex-wrap compared with a CSS grid auto-fit layout
With flex-wrap the last row stretches; with grid every card keeps its column width.

Flexbox still has a job here. Inside each card, a column flexbox keeps the button at the bottom even when one product title runs to two lines:

.card {
  display: flex;
  flex-direction: column;
}
.card .buy-button {
  margin-top: auto;
}

Using Flexbox and Grid Together on One Page

Take a clothing store page of the kind many small Pakistani brands now run on Shopify or WordPress. Here's how a developer might split it up. This is a worked example, not a rule:

Page section Tool Why
Overall frame (header, filters, products, footer) Grid Areas must stay in place and rearrange on phones
Header bar Flexbox Logo, search and cart icon sit on one line
Size and color filters Flexbox with wrap Chips vary in width and wrap naturally
Product gallery Grid Columns must line up across rows
Inside each product card Flexbox (column) Button pinned to the bottom
Footer link columns Grid Equal columns that collapse to one on phones

When you're asked to fix a messy client theme, this kind of split is often the cleanest repair. Many WordPress themes still mix old floats with flexbox, and rebuilding one section at a time with the right tool is safer than rewriting everything.

Subgrid for Cards That Must Match

One more feature is worth learning: CSS subgrid. With grid-template-rows: subgrid, each card can borrow its rows from the parent grid. Titles, prices and buttons then line up across neighboring cards, even when the text lengths differ. Can I Use lists subgrid support at 94.68% globally, covering Chrome and Edge 117+, Firefox 71+ and Safari 16+.

Browser Support in 2026: Is Anything Still Risky?

For flexbox, grid and gap, no. The figures in the table above show both layouts work for over 97% of global users. You can build with them without fallbacks.

The one feature to treat carefully is masonry, the Pinterest-style layout where cards of different heights pack together. The final syntax is display: grid-lanes. The WebKit team's January 2026 post on Grid Lanes said Chrome and Edge 140 had it behind a flag since July 2025. Can I Use now lists grid-lanes as supported in Safari 26.4 and later, with Chrome, Edge and Firefox still behind flags, for 11.3% global support.

The safe pattern is to declare a normal grid first and grid-lanes second. Browsers that don't understand the second line simply ignore it:

.gallery {
  display: grid;
  display: grid-lanes;
}

Until Chrome, Edge and Firefox switch it on by default, their users will see the regular grid version. Test that version properly, because many of your visitors will get it.

Myths That Confuse Beginners

A lot of old tutorials and forum answers still circulate. These four come up in almost every new batch:

Four flexbox and grid myths checked against MDN and Can I Use
Four common beginner myths, with what the documentation actually says.

"Grid replaced flexbox." It didn't. MDN notes the two share many properties and values, and they're designed to work side by side.

"Flexbox is for small parts and grid is for big ones." MDN says there are no set rules like that. A tiny form row can need grid, and a full-width header can be pure flexbox. Ask the one-or-two-dimensions question instead.

"The gap property only works in grid." MDN's reference confirms gap works in flex containers too, so you can drop most margin tricks between items.

"Masonry always needs a JavaScript library." Not for much longer. Grid lanes is arriving natively, with Safari first. Until other browsers ship it, a plain grid fallback keeps the page usable.

Which Should You Learn First for Jobs and Freelancing in Pakistan?

In the flexbox vs grid learning order, start with flexbox and move to grid the same week. Flexbox gives you quick wins on headers, buttons and cards, which builds confidence. Grid then feels like a natural next step instead of a separate subject.

Don't expect grid to feel easy straight away, and don't take it as a sign you're slow. In the State of CSS 2025 survey, grid was the most common layout pain point, with 272 answers against 125 for flexbox issues. The same survey had grid named as a game-changing feature 461 times, more than twice flexbox's 211. Hard at first, and worth it.

Here's a practical way to learn CSS layout that fits around college or a day job:

  1. Days 1 to 2: Build a header, a button group and a centered login box with flexbox.
  2. Days 3 to 4: Build a product gallery with repeat(auto-fit, minmax()) and a page shell with named areas.
  3. Day 5: Combine them into one responsive landing page for a real local business, such as a bakery or tuition center.
  4. Days 6 to 7: Test it on two phones and one laptop, fix what breaks, and upload it to your portfolio.

That one page shows a client on Fiverr or Upwork more than a certificate alone. If you want a wider plan for what comes after CSS, our frontend developer roadmap for Pakistan lays out the next steps, and React projects for beginners gives you portfolio ideas once JavaScript clicks.

Junior frontend interviews can include a flexbox vs grid question. A clear answer, with an example like the card row above, tells them you've built real layouts rather than copied snippets.

Practicing Layouts in PSTA's Full-Stack Course

Responsive web design is part of the first module of PSTA's Full-Stack Web Development Course with AI Tools, which covers HTML5, CSS3, Flexbox and Grid before moving to JavaScript, React, Node.js, MongoDB, PHP and WordPress. The first project listed is a multi-page business website. It has to work on phones, tablets and desktops, so you practice these decisions on a real build.

The details, as listed on the course page today:

  • Duration: 6 months, beginner-friendly, no coding experience needed
  • Fee: Rs. 45,000 (regular Rs. 60,000), payable in 2 installments
  • Modes: on campus in Abbottabad, live online anywhere in Pakistan with recorded classes, or a hybrid of both
  • Batches: a new one starts every month, with morning, afternoon, evening and weekend slots

If you'd prefer to go deeper on the scripting side, there's a separate JavaScript course, and the WordPress course suits people who mainly build sites for local clients. Compare all options on the full course list, read how enrollment works on the admission page, or send a WhatsApp message to +92 314 5424399 to check which class slot suits your routine.

Rebuild One Section of a Site You Use Daily

Pick a website you open every day, perhaps your university portal or a shop you buy from. Choose one section, such as its header or a row of cards, and rebuild it from scratch. Before writing any CSS, decide: one dimension or two? Then build it with that tool, and try the other one afterwards to see where it struggles. Twenty minutes of this teaches more than an hour of reading about it.

Frequently asked questions

Is CSS grid better than flexbox?

Neither is better overall. They solve different problems. Flexbox handles one row or one column where the content sets the size, such as a navbar or a group of buttons. Grid handles rows and columns that must line up together, such as a page frame or a product gallery. Most professional pages use both, each in the section it suits.

Can I use flexbox and grid together on the same page?

Yes, and that is the normal way to build a modern page. A common pattern is grid for the outer frame and the product gallery, with flexbox inside the header, the filter chips and each card. An element can be a grid item and a flex container at the same time, so the two nest without any conflict.

Should beginners learn flexbox or grid first?

Start with flexbox, because it gives quick results on headers, buttons and cards. Move to grid within the same week so you don't fall into the habit of forcing flexbox into two-dimensional layouts. A good test of progress is building one landing page that uses grid for its sections and flexbox inside them.

Is flexbox or grid better for responsive design?

Both are built for responsive layouts. Grid with repeat(auto-fit, minmax()) can reflow a gallery without media queries, and grid-template-areas lets you rearrange a whole page by changing a few lines. Flexbox with flex-wrap lets items fall onto new lines as space runs out. Pick based on whether you need one dimension or two.

Do I still need media queries with CSS grid?

Sometimes. A card gallery built with auto-fit and minmax() adapts on its own, so it often needs no media query. Page shells that change their structure, such as moving a sidebar below the main content on phones, still use a media query to swap the grid-template-areas. Container queries are another option for components.

Is CSS masonry layout supported in browsers yet?

Partly. The final syntax is display: grid-lanes. Can I Use lists it as supported in Safari 26.4 and later, while Chrome, Edge and Firefox still keep it behind flags. Declare display: grid first and display: grid-lanes second, so browsers without support fall back to a normal grid that still looks tidy.

Sources & references

  1. Relationship of grid layout to other layout methods (MDN) developer.mozilla.org
  2. Relationship of flexbox to other layout methods (MDN) developer.mozilla.org
  3. gap CSS property (MDN) developer.mozilla.org
  4. CSS Grid Layout (Can I use) caniuse.com
  5. CSS Subgrid (Can I use) caniuse.com
  6. CSS Grid Lanes (Can I use) caniuse.com
  7. When will CSS Grid Lanes arrive? (WebKit) webkit.org
  8. State of CSS 2025: Features 2025.stateofcss.com

Last reviewed & updated on by Umar Qureshi. Written by the PSTA team in Abbottabad, Pakistan.

Share this article
Umar Qureshi
About the author

Umar Qureshi

Computer Science Teacher & Full-Stack Developer at Professional Skills & Tech Academy

Umar Qureshi, known to his students as Sir Umar Qureshi, is a computer science teacher, full-stack developer and SaaS builder from Abbottabad, Pakistan, with 10+ years in the classroom. At PSTA he teaches web development, Python and data science, AI and automation, Power BI, digital marketing and office automation, on campus and in live online classes. He built two live platforms end to end: the PSTA website and learning platform (admissions, student login and verifiable certificates) and OnePlace (oneplace.com.pk), a multi-vendor marketplace and e-commerce SaaS for Pakistani sellers. He teaches the tools he uses to build real products, so every lesson ends with a project students can show. Official website: https://sirumarqureshi.com

Full-Stack Web Development Course with AI Tools course at PSTA
Recommended course

Full-Stack Web Development Course with AI Tools

Turn this guide into a career: hands-on training with real projects, online across Pakistan or on-campus in Abbottabad · 6 Months.

Rs. 45,000 Rs. 60,000

Comments

No comments yet — ask a question or share your experience.

Leave a comment

Comments are moderated. Please be respectful — no links to spam.

Chat with us