CSS Grid vs Flexbox - A Complete Comparison

Published:

|

Updated:

Web design has evolved drastically over the past years — from simple website layouts to complex designs. And it's crucial to keep your CSS knowledge updated to employ the correct CSS layout to create professional and responsive web designs.

The two crucial CSS layout systems you should be comfortable working with are CSS Grid and CSS Flexbox. Both allow you to create pixel-perfect, flexible, and responsive website designs.

In this complete comparison of CSS Grid and Flexbox, you'll learn their differences, pros and cons, and use cases.

As a bonus, I've briefly explained how to use both layouts to help you get up and running quickly with them. If you'd like to dive even deeper, you can find a tutorial link at the end of this article that utilizes both Flexbox and Grid.

Let's begin.

CSS Grid vs Flexbox - A Complete Comparison

Introduction

Let me briefly explain how website designs were traditionally created before the advent of modern layout systems like Flexbox and Grid.

Web designers relied on a combination of various CSS properties and features like position, float, and the HTML Table element to create complex and multi-column website layouts.

While these methods achieved the desired website looks, they lacked some features — such as vertically centering an element inside a container.

Such methods are "CSS hacks" as they require you to fine-tune your web pages for different devices and screen dimensions, increasing coding efforts and potential design flaws.

As a result, you end up with dozens of CSS codes — and possibly duplicate code — most of which would be hard-coded styles for different sections and pages.

To overcome such cumbersome issues, Flexbox and CSS Grid provide several standard properties to create fluid and intricate layouts using just a few lines of code, among other benefits. And ultimately, the CSS code becomes clean, easily maintainable, and highly reusable.

CSS Flexbox Introduction

The Flexbox — CSS Flexible Box Layout — is a one-dimensional layout system that uses only either rows or columns to place HTML elements on the web page.

Its early specs and technical implementations began in 2009, and it became a W3C Candidate Recommendation (CR) in 2012, eventually becoming a W3C Recommendation in October 2017.

As the name suggests, it's a flexible design system that automatically adjusts the size and position of elements on different screen sizes.

For example, CSS Flex can automatically shrink and wrap horizontal (row) items as the browser viewport width gets smaller.

You may notice that Flexbox is relatively easier to use than Grid, especially if you're a beginner.

Key Concepts and Terminologies of Flexbox

The term flex container refers to an element that's a flexbox (with display: flex; or display: inline-flex; property). All children (child elements) of flex containers are called flex items.

At its core, Flexbox utilizes axes — the main axis and the cross axis (perpendicular to the main axis). The main axis is the horizontal or inline direction along which the flex items are added.

When the flex direction is set to column, the axes interchange — the main axis becomes vertical or block, and the cross axis becomes horizontal or inline.

Important Flexbox Properties

Below are some important Flex properties that you ought to be familiar with:

  • flex-direction — The direction in which the flex items are laid out (horizontal or vertical). It also indicates if the items are reversed.
  • flex-wrap — Whether the items are single-line (possibly horizontal overflow) or multi-line (stacked on smaller screens).
  • flex-flow — A shorthand property comprising flex-direction and flex-wrap properties. The first value sets flex-direction, and the second value sets the flex-wrap behavior.
  • order — An integer value that specifies the order or placement of items in the container. For instance, an item with an order value of 1 appears before an item with an order value of 2. This property is also supported in grid containers.
  • gap — The gutter or gap between the elements. This property is also supported in grid containers.

Refer to this MDN glossary page for detailed specifications and more properties.

CSS Grid Introduction

The CSS Grid is a two-dimensional layout system that uses both — rows and columns to place HTML elements on the web page.

Its initial Working Drafts (WD) were published in 2011, and it became a W3C CR in 2012, eventually becoming a W3C Recommendation in 2017.

Like Flexbox, Grid is also a responsive layout that can automatically adjust the size and position of elements for different screen resolutions and devices.

You can create complex and accurate website designs using Grid since it gives you more design control over Flexbox.

Key Concepts and Terminologies of Grid

The term grid container refers to an element that's a grid (with display: grid; or display: inline-grid; property). All children (child elements) of grid containers are called grid items.

Unlike flexbox where items flow in only one direction, grid items are laid out in both directions — columns and rows — giving explicit control for placing elements.

A grid container has grid lines that intersect horizontal and vertical space — creating grid cells called grid areas where content goes.

There are two types of grid lines — vertical grid lines for grid columns and horizontal grid lines for grid rows.

Furthermore, there are two types of grids — implicit and explicit. You can use either only one type or mix both — the choice is yours.

In brief, you can create an explicit grid using the grid-template-* properties, and an implicit grid using the grid-auto-* properties. The former properties allow you to specify an explicit number of columns and rows, while the latter ones automatically create rows or columns for grid items as needed.

Because the grid system uses both axes to place content, you can use it to create complex and responsive page designs.

Important Grid Properties

Here are some important Grid properties that you should know:

Head over to this MDN glossary page for more information and other properties.

A Common Property — CSS Gap

One common similarity between both layouts is the CSS Gap property. Both grid and flexbox containers support the gap property.

In addition, you can also set the gap on multi-column elements (a different kind of layout system).

The key benefit of using CSS Gap for spacing is that gutters are distributed uniformly among the container elements.

Unlike margin or padding where you need to manually calculate the spacing for elements — which may not be accurate or ideal in some cases — browsers automatically calculate the correct gap value needed to distribute equal spacing among the container children.

Read this detailed comparison article that illustrates the major differences among CSS Margin, CSS Padding, and CSS Gap.

Browser Support for Flexbox and CSS Grid Layouts

Generally, it's safe to use both Flex and Grid for your website projects as they are widely supported and used.

However, before you use either of them, it's still recommended to check the browser and device support to prevent any issues for your target audience — such as broken website designs.

According to Can I use, the global usage and major browsers support for both CSS Flexible Box Layout and CSS Grid are the following (as of writing this article):

Differences between Grid and Flexbox

Let me quickly summarize the key differences (or similarities) between Flexbox and Grid.

Flexbox Layout Features

Below are the key highlights of the Flexbox layout:

  • It operates in 1 dimension.
  • It places items in only one direction — either horizontally or vertically.
  • It can wrap items to prevent horizontal overflow.
  • It can use gaps or gutters to create uniform space between items.

Grid Layout Features

Below are the key highlights of the Grid layout:

  • It operates in 2 dimensions.
  • It can place items in both directions — horizontally and vertically.
  • It can create a rigid container or structure that doesn't change regardless of the screen dimensions.
  • It can use gaps or gutters to create uniform space between items.

When to Use CSS Grid

As a recommendation, use Grid:

  • When you need to create a multi-column page layout with two or more columns.
  • When you need a rigid layout structure irrespective of browser viewport size.
  • When you need greater and more precise control over your site design or when placing elements.
  • For major and bigger parts of your site, such as sections or containers that accommodate various elements, such as headings, paragraphs, images, etc.

When to Use Flexbox

As a rule of thumb, use Flex:

  • When you need to create simple and linear-style site designs.
  • When you need to align content (vertically or horizontally), such as an icon with some text.
  • When you need to adjust an element's position within another flex or grid container (left, right, or center justification).
  • For minor and smaller parts of your site, such as icons, text snippets, or other elements that are independent or free form.

A Quick Brief on CSS Box Model

Before you learn about using Grid and Flex, you should be familiar with the CSS Box Model — a key concept to understand how the HTML elements render and behave on the webpage.

Every HTML element is rectangular and has a box around it — called the box model. This box plays an important role when you want to apply some CSS to any HTML element.

The box model comprises the following:

  • Content (where the actual HTML element or content resides)
  • Padding
  • Border
  • Margin
  • Width (determines the size of the content area)
  • Height (determines the size of the content area)

The CSS Box Model behaves and renders differently depending on the box-sizing property value. Understanding the box-sizing property is crucial as it defines how the element's width and height are calculated. Learn more about this property on MDN.

Bonus Tutorial — Using Flexbox and Grid

It's time to see Grid and Flex in action. Let's go over the steps needed to create a layout using Grid or Flex.

Step 1 — Adding the HTML Markup

I'll use the following boilerplate HTML code (you can use this or continue with your code as you wish).

Copy and paste the following HTML markup into a new file and save it as index.html.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>CSS Grid vs Flexbox - A Complete Comparison</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./styles.css">
</head>

<body>

  <main>
    <section class="container">
      <p class="paragraph-1">This is paragraph 1.</p>
      <p class="paragraph-2">This is paragraph 2.</p>
      <p class="paragraph-3">This is paragraph 3.</p>
    </section>
  </main>

</body>

</html>

Step 2 — Adding the CSS Styles

First, I'll use some styles to improve the page layout. And a different background color for each column to help visualize it.

Copy and paste the following CSS code into a new file and save it as styles.css in the same folder as the index.html file.

body {
  background-color: #f0faf6;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 20px;
  margin: 0;
  padding: 32px;
}

p {
  margin: 0;
  padding: 32px;
  border-radius: 12px;
}

.paragraph-1 {
  background-color: #ebcb8b;
}

.paragraph-2 {
  background-color: #a3be8c;
}

.paragraph-3 {
  background-color: #b48ead;
}

The first column (paragraph 1) has a pale orange color, the second one (paragraph 2) has a sage green color, and the third one (paragraph 3) has a lavender gray color.

Using Flexbox

For Flexbox layout, copy and paste the following code in the styles.css file:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 16px;
}
Flexbox — Elements placed in a multi-column layout.
Flexbox — Elements placed in a multi-column layout.
View Original Image Size

Using Grid

For Grid layout, copy and paste the following code in the styles.css file:

.container {
  display: grid;
  align-items: center;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}
Grid — Elements placed in a multi-column layout.
Grid — Elements placed in a multi-column layout.
View Original Image Size

Step 3 — Testing the Responsive Layout System Using Grid and Flexbox

After creating the markup and style files, open the page you created above (index.html) and resize the browser width (shrink or expand) to see the responsive layout in action.

For Flex, notice how the elements are resized to shrink or grow to adjust to the available container space. As the viewport width becomes smaller, the elements wrap to prevent horizontal overflow.

Flexbox — Elements stacked on each other on a small screen.
Flexbox — Elements stacked on each other on a small screen.
View Original Image Size

For Grid, notice how the columns are stacked on each other as the screen size gets smaller.

Grid — Columns stacked on each other on a small screen.
Grid — Columns stacked on each other on a small screen.
View Original Image Size

Adjusting the Size and Behavior of Container Items

Depending on whether you Flex or Grid, you'll notice a different size for the columns.

For instance, Grid increases the element's width to fit the available space in each column track. On the other hand, Flex adjusts the element's width to be as maximum as its content's width (in this case, the paragraph text).

Of course, you can adjust this sizing and other behaviors using various properties of each layout. For example, if you set flex-grow: 1; on the flex child elements (p HTML tag, in this case), the flex children will grow in size to take the available container space.

Setting flex-grow property value to 1 on flex children.
Setting flex-grow property value to 1 on flex children.
View Original Image Size

Conclusion

That wraps up the comparison of CSS Grid and CSS Flexbox. I hope you learned the key differences between Flex and Grid and cleared up any confusion you might have had.

Which layout do you use often and why? Let me know your thoughts via X (formerly Twitter) by mentioning me @iamdanialzahid.

Related Article

Here is a related article that uses both CSS Grid and Flexbox to further deepen your understanding: Responsive Two Column Layout Using CSS and HTML

FAQs Regarding Flexbox vs Grid

Is CSS Grid better than Flexbox?

No, CSS Grid is not better than Flexbox. Both Flexbox and Grid have their use cases and applications.

You can use just one layout system or a mix of both — the choice mostly depends on your needs and overall web design requirements.

Should I learn CSS Grid or Flexbox first?

If you're beginning to learn, I'd advise Flexbox first because of its simplicity and easier learning curve.

Once you get the hang of Flexbox, move on to CSS Grid.

What is the disadvantage of CSS Flexbox?

Personally speaking, the only disadvantage of CSS Flexbox is its 1-dimension space. You can only lay out items either horizontally (rows) or vertically (columns).

If you need to place items in both axes (vertical and horizontal), you need to use Grid.

Additional Resources

Below are a few links if you'd like to explore some of the topics mentioned above.

Contents

    Danial Zahid's headshot.

    About Danial Zahid

    I'm a self-taught web developer passionate about everything related to websites and web development. Over the past years, I've explored and worked with different web technologies and tools, notably WordPress, Eleventy, npm, and Gulp.js, to name a few.

    In addition, I've created and currently maintain several open-source projects, including web apps, widgets, websites, and more.

    When I'm not writing content for W3Things or doing web development work, I enjoy my free time by playing games or listening to podcasts.

    Get Essential Gulp Kit

    The ultimate Gulp.js solution to improve your developer experience.

    • Includes complete Gulp.js toolkit setup
    • Optimize website content and static assets
    • Continuous asset optimization during development phase
    • Optimize unlimited number of files in bulk
    • Plus many more awesome features

    Subscribe to the Newsletter

    This website uses cookies to optimize your site experience. By continuing to use the site, you are agreeing to its privacy policy and the use of cookies.