CSS Grid vs Flexbox: Which to Choose and When

Tahera Alam

Posted On: May 7, 2024

view count125578 Views

Read time36 Min Read

Layout is one of the most important aspects of web design. It determines how the elements of a web page are arranged and displayed. This is where CSS Grid and Flexbox come into play – two powerful CSS layout features that help design how content appears on a webpage.

CSS Grid is a two-dimensional layout system that can help you lay out things neatly in horizontal and vertical dimensions. It is ideal for creating layouts where you want precise control over the position of elements. For example, you can use CSS Grid to create a magazine-style layout with equal-width columns or a flexible layout for images where the content can be displayed in different sizes. As shown in the image below.

CSS Grid is a two-dimensional layout system

Source

On the other hand, Flexbox is one-dimensional and excels in arranging things in horizontal or vertical dimensions. It makes it great for creating navigation menus, lists, or groups of cards.

In this blog, we will learn everything you need to know before deciding between using a CSS Grid or a Flexbox. By the end of this blog, you’ll have a solid understanding of when and how to use a CSS Grid or a Flexbox.

So, let’s get started!

Understanding CSS Grid

CSS Grid Layout (also known as CSS Grid) is a system that allows for two-dimensional layouts to be created on the web. CSS Grid makes creating responsive and flexible designs easier without relying heavily on complex positioning or float-based layouts.

CSS Grid works by dividing a container element into a grid of rows and columns. The child elements of the container are then placed into the grid, either automatically or by explicitly specifying their position. There are two main ways to place elements in a grid container:

  • Automatic placement: This is the default mode, and it means that the browser will automatically place the elements in the grid according to their size and the size of the grid.
  • Explicit placement: This mode allows you to specify the exact position of each element in the grid.

This flexibility in content placement makes the grid an ideal choice for creating complex layouts where you need to lay out elements in horizontal and vertical dimensions with precise control over the position of elements.

Below is a visualization of how a two-dimensional layout might look like:

visualization of how a two-dimensional layout might look like

In the below section of this blog on CSS Grid vs Flexbox, we will learn the key properties of CSS in detail.

Key Properties of CSS Grid

Before delving into the specific properties of CSS Grid, let’s take a moment to understand what makes it so useful.

In the past, creating complex multi-dimensional web layouts was challenging, involving complex hacks and workarounds to achieve the desired structure. However, CSS Grid has changed that by providing a straightforward way to arrange content into grids, making it easier to control the placement and alignment of elements.

It does this using key properties, including defining a grid container with display: grid, specifying the number of rows and columns using grid-template-rows and grid-template-columns, and aligning items within the grid using properties like justify-items and align-items.

These properties provide fine-grained control over web layouts, making creating responsive and complex designs easier.

Let’s now explore these properties in more detail:

display:grid

This is the property that we use to create a grid container. A grid container is just an HTML element we use to create a grid layout. It establishes a grid formatting context and allows us to organize child elements into a grid structure.

To create a grid container, simply use the display property with the value grid or inline-grid. Here’s an example:

HTML:

CSS:

Now that we know how to create a grid layout let’s move on to see how to define rows and columns in a grid layout.

grid-template-columns

The grid-template-columns property specifies the number and width of columns in a grid layout. The values are a space-separated list, where each value specifies the width of the respective column.

For example, the following line would create a grid layout with two columns, each of which is 100px wide:

 following line would create a grid layout with two columns

You can also use the repeat() function to create a repeating pattern of columns. For example, the following code would create a grid layout with three columns, each of which is 100px wide:

grid-template-rows

Like grid-template-columns, the grid-template-rows property specifies the number and heights of rows in a grid layout. Each value specifies the height of the respective row.

For instance, the following line would create a grid with two rows of 100-px height:

create a grid with two rows of 100-px height

Now that we understand how to define rows and columns in a grid layout, let’s learn how to use both grid-template-columns and grid-template-rows properties together with a practical example:

HTML:

CSS:

See the Pen
grid-template-rows & grid-template-columns demo
by Tahera Alam (@alam_tahera)
on CodePen.

Result:

grid-container element with two equal-sized columns

The above example has a .grid-container element with two equal-sized columns. We use grid-template-columns to define the grid with two columns, each taking up an equal fraction of available space, creating a two-column layout.

To lay out the second column with the .cards class, we use another grid where we specify two columns and three rows using the below lines:

The grid-template-columns property sets the width of each column using the 1fr unit, which divides the available space equally between both columns. Similarly, the grid-template-rows property sets the height of the rows, with the first row being 300 pixels, the second row being 350 pixels, and the third row being 380 pixels.

justify-items

Like Flexbox, CSS Grid also provides an array of properties for controlling the alignment and positioning of grid items. One of these key properties is justify-items.

But, before discussing justify-items, let’s take a moment to learn all the essential properties related to alignment below.

Property Description
justify-items Align grid items along the inline axis (horizontally) within their cell.
align-items Aligns grid items along the block axis (vertically) within their cell.
place-items Shorthand for align-items and justify-items in one declaration.
justify-content Align the grid along the inline axis (horizontally) within the grid container, including extra space, if any.
align-content Align the grid along the block axis (vertically) within the grid container.
place-content Shorthand for align-content and justify-content in one declaration.
justify-self Aligns a single grid item along the inline axis within its cell.
align-self Aligns a single grid item along the block axis within its cell.
place-self Shorthand for align-self and justify-self in one declaration.

The justify-items property aligns grid items along the row (inline) axis. It applies to all grid items within the grid container.

Below are the values you can use with the justify-items property:

  • start: Align items to the start of the grid cell.
  • end: Align items to the end of the grid cell.
  • center: Align items to the center of the grid cell.
  • stretch: This is the default value and expands items to fill the entire height of the grid cell.

Let’s look at an example to demonstrate this:

HTML:

CSS:

JavaScript:

See the Pen
justify-items demo
by Tahera Alam (@alam_tahera)
on CodePen.

Result:

justify item demo

As we have understood the key properties above, in the below section of this blog on CSS Grid vs Flexbox, we will learn some of the benefits of CSS Grid in detail.

Benefits of CSS Grid

CSS Grid offers several benefits, making it an excellent choice for creating complex and grid-based layouts. Let’s take a look at some of them:

Two-dimensional layout

Unlike traditional layout methods focusing on rows or columns, CSS Grid allows you to simultaneously create complex layouts in both dimensions. This makes it ideal for arranging items in a grid format, such as magazine-style designs or responsive grid systems.

Overlap and layering

CSS Grid is great for overlapping elements and layering them on top of each other. To overlap elements in CSS Grid, you can use the grid-area property. The grid-area property specifies the grid area that an element should occupy. You can specify the area of the grid using a combination of row and column numbers.

For example, the following CSS code would overlap two elements:

This method is useful for creating intricate designs and visual effects that would be challenging to achieve with other layout methods.

Flexible sizing

CSS Grid allows you to use flexible units like fr (fractional unit) to define column and row sizes. The fr unit represents a fraction of the available space. For example, the following code would create a grid with three columns that are all the same width:

This is particularly useful for distributing available space proportionally among grid items. To learn more about fr (fractional unit) in CSS, follow this guide on CSS units and get detailed insights.

Let’s look at the below visualization to understand it better:

CSS Grid allows you to use flexible units like fr

Credits to: ChrisStaud

Reduced HTML nesting

CSS Grid reduces the need for complex nested HTML structures common with other layout methods. This can lead to cleaner and more maintainable code.

In the traditional approach to creating layouts, you often used HTML elements like <div> or <section> to structure your page into rows and columns. For example, if you want to create a grid-like layout, you might have to create several nested <div> elements to define the rows and columns of your grid. This can lead to much extra HTML code, making your structure more complex and harder to manage.

With CSS Grid, instead of adding extra HTML elements to define your grid structure, you can define rows and columns directly in your stylesheet using properties like grid-template-columns and grid-template-rows. This means you can create rows and columns without nested HTML elements, making your code cleaner and maintainable.

In the below section of this blog on CSS Grid vs Flexbox, we will learn real-world examples where CSS Grid is implemented and currently being adapted and used.

Real-World Examples of CSS Grid

CSS Grid plays a crucial role in contemporary web design because of Its ability to create intricate and responsive layouts. Below, we explore some real-world websites that leverage CSS Grid to achieve sophisticated and responsive designs:

Airbnb: Airbnb, a popular online marketplace for vacation rentals and lodging, utilizes CSS Grid in its layout to organize property listings, search results, and filters, allowing users to navigate and explore available accommodations easily.

Airbnb utilizes CSS Grid in its layout to organize property listings

It is essential to make your website responsive on all devices and screen sizes. One significant aspect of achieving this responsiveness is adopting a mobile-first design approach, where you prioritize designing for mobile devices and progressively enhance the experience for larger screens.

Leading businesses widely embrace this approach. For instance, below is the Airbnb website rendered on different screen sizes:

businesses widely embrace

You can ensure your website is responsive across different screen sizes by using a cloud-based platform like LambdaTest. It’s a platform that allows you to run manual and automated tests on over 3000 real devices, browsers, and operating system combinations. One of its features, LT Browser, helps you check your website’s responsiveness. We will delve into this feature in more detail later.

Info Note

Test the responsiveness of your website across 53+ device viewports. Try LT Browser now!

National Geographic: National Geographic’s website uses CSS Grid to organize and display its visually rich content, including articles, images, and videos, in a structured and visually appealing manner.

National Geographic

The New York Times: The New York Times, a prominent news organization, uses CSS Grid for its homepage layout and various article pages to present diverse content in a clean and organized grid format.

The New York Times

Now that we have a clear understanding of CSS Grid and its benefits with real-world examples, in the below section of this blog on CSS Grid vs Flexbox, we will learn everything about CSS Flexbox in detail.

Understanding CSS Flexbox

CSS Flexbox, also known as the CSS Flexible Box Layout, was introduced in 2009. It emerged to address the complexities and limitations of traditional layout models, offering developers a more efficient and intuitive way to design responsive and dynamic web layouts.

Flexbox is a one-dimensional layout system that allows you to distribute and arrange a group of items in rows or columns. By one-dimensional, we mean it deals with rows or columns at a time but not both. It makes it particularly well-suited for distributing content along a single axis(either horizontal or vertical).

In the below section of this blog on CSS Grid vs Flexbox, we will learn the key properties of Flexbox in detail.

Key Properties of Flexbox

Understanding when to use Flexbox and how it works is essential. In this section, we will explore its essential properties and discuss how Flexbox works.

CSS consists of many different layout algorithms, known as “layout modes.” Every layout mode in CSS is like its own tiny sub-language with different characteristics. The default layout mode is Flow layout, but we can opt into Flexbox by changing the display property on the parent container.

display:flex

display:flex is the property we use to make a container a flex container.

When you apply display: flex; to a container, it becomes a flex container, and its immediate children become flex items. The container’s direct children are treated as flex items and are laid out according to the rules of Flexbox.

Below is an example:

HTML:

CSS:

JavaScript:

See the Pen
display flex demo
by Tahera Alam (@alam_tahera)
on CodePen.

Result:

block layout

In this example, we have a container(with the class .grid-container) and a few child elements inside it.

By default, the container has a block layout that stacks the child elements vertically, creating a column-like structure. But when we change the container’s display to flex, it creates a flex formatting context and arranges all the child elements in a row, side by side according to the default flexbox layout algorithm.

Let’s now see how we can change this default behavior of Flexbox using the next property.

flex-direction

By default, items of a flex container will stack side by side in a row, but you can change that using the flex-direction property.

The most commonly used flex directions are row and column. Setting the flex-direction to a row will arrange elements from left to right, and setting it to a column will arrange elements in a column from top to bottom.

column-reverse

You can also use row-reverse and column-reverse to reverse the elements’ directions, but these have limited practical applications and are rarely used.

When you set the flex direction to row-reverse, the elements are laid out from right to left. The first item is at the right end, and the subsequent items follow towards the left.

Similarly, with flex-direction set to column-reverse, the items will be positioned in a column from bottom to top instead of top to bottom.

An important thing to understand here is the concept of axis, which plays a pivotal role in how flex layouts work. When you set the flex-direction property, you define the flex container’s main axis and cross-axis.

The main axis is along which the flex items are laid out inside a flex container. The cross axis is the axis perpendicular to the main axis.

If you set flex-direction to row, the main axis will run horizontally, and the cross axis will run vertically. In this case, elements will align along the main axis in a row, from left to right.

On the other hand, if you use flex-direction: column, the main axis will run vertically from top to bottom, and the cross axis will run horizontally from left to right. The elements will stack up along the main axis in a column, from top to bottom.

Here’s a quick visualization of both the scenarios:

flex-direction

justify-content

The justify-content property controls the alignment and distribution of flex items along the flex container’s main axis.

It provides several options that allow us to position and distribute items within the container. We can group all the items in a specific place using flex-start, center, and flex-end properties, or we can space them out using space-between, space-around, and space-evenly.

Here are the possible values for the justify-content property:

  • flex-start: This is the default value. It aligns flex items at the beginning of the container’s main axis.
  • flex-end: This aligns flex items at the end of the container’s main axis.
  • center: It centers flex items along the main axis of the container.
  • space-between: This value distributes flex items evenly along the main axis, leaving no space before the first item and after the last item.
  • space-around: This distributes flex items evenly along the main axis with equal space before the first item and after the previous item. The space between the remaining items is also equal.
  • space-evenly: This distributes flex items evenly along the main axis with equal space between them, including before the first item and after the last item.

Let’s look at an example to understand this:

HTML:

CSS:

JavaScript:

See the Pen
justify content demo
by Tahera Alam (@alam_tahera)
on CodePen.

Result:

align-items

align-items

The align-items property controls flex items’ alignment along the flex container’s cross-axis. The cross axis is perpendicular to the main axis, which, as we mentioned, is determined by the flex-direction property.

The align-items property allows us to align items vertically (if the main axis is horizontal) or horizontally (if the main axis is vertical).

Here are the values for the align-items property:

  • stretch: This is the default value for the cross-axis alignment. It causes flex items to stretch along the cross-axis to fill the container’s height (if the main axis is horizontal) or width (if the main axis is vertical).
  • flex-start: It aligns flex items at the start of the cross-axis.
  • flex-end: This aligns flex items at the end of the cross-axis.
  • center: It centers flex items along the cross-axis.
  • baseline: This aligns flex items such that their baselines are aligned.

Let’s look at an example to visualize this:

HTML:

CSS:

JavaScript:

See the Pen
align-items demo
by Tahera Alam (@alam_tahera)
on CodePen.

Result:

Flexbox

As we understand the key properties above, in the below section of this blog on CSS Grid vs Flexbox, we will learn some of the benefits of Flexbox in detail.

Benefits of Flexbox

Flexbox offers many benefits that streamline how we structure and design layouts. Let’s take a look at some of these benefits to see how they can be used to create flexible web layouts:

Efficient for aligning and distributing content

Flexbox is extremely handy for aligning and distributing elements within containers. Its properties, such as justify-content and align-items, make horizontal and vertical alignment effortless.


Simplifies responsive design

Flexbox makes creating responsive layouts that adapt to different screen sizes easily. One of the key features that facilitate this responsive design using flexbox is its ability to control the behavior of items within a container using properties like flex-wrap, flex-grow, flex-shrink, and flex-basis.

Let’s briefly break down each of these properties to understand how they help in making a layout responsive:

  • flex-wrap: This property determines whether items should wrap to the next line when there’s insufficient space within the container. By utilizing this property, you can ensure that elements rearrange themselves neatly as the screen size changes.
  • flex-grow: This property specifies how much an item should grow about its siblings when there’s extra space available within the container.
  • By assigning appropriate flex-grow values to different items, you can control which elements expand more than others, distributing space efficiently and maintaining a balanced layout.

  • flex-shrink: In cases where the container becomes too narrow to accommodate all items at their specified sizes, the flex-shrink property determines the degree to which each item should shrink. This avoids overflowing content and maintains the overall layout structure.
  • flex-basis: This property sets the initial size of an item before any available space is distributed. By using it, you can establish a starting point for item sizes, preventing unexpected sizing behaviors.
  • Creating a responsive website requires careful consideration of key factors to avoid common issues. Follow this blog on best practices for responsive websites to ensure they are effective and user-friendly. By using these flexbox properties, you can create layouts that adapt to different screen sizes and devices without having to write extensive media queries.

    Auto-adjustment of container items

    Flexbox automatically adjusts the size of items within a flex container to fit the available space. This eliminates the need for setting fixed widths or heights for each element, making the layout more adaptable to varying content lengths.

    Below is an example:

    HTML:

    CSS:

    See the Pen
    flexbox auto-adjustment demo
    by Tahera Alam (@alam_tahera)
    on CodePen.

    Result:

    Result

    In the example, the .card-container uses a Flexbox to create a row of cards. The .card elements automatically adjust their heights based on the content inside them. Even though the content within the cards varies in length, Flexbox ensures that the cards have equal height and maintain a neat and organized layout.

    In the below section of this blog on CSS Grid vs Flexbox, we will learn real-world examples where Flexbox is implemented and currently being adapted and used.

    Real-World Examples of Flexbox

    Flexbox is widely employed in modern web design for its versatility and efficiency. In fact, it’s rare to encounter a website that doesn’t rely on Flexbox to organize and present content neatly. Here are some real-world examples showcasing its effectiveness:

    Amazon: Amazon, the largest eCommerce platform in the world, uses Flexbox in its layout to make it responsive and user-friendly:

    Amazon

    Apple: Apple, the technology giant, makes extensive use of flexbox in its layout to make it sleek and eye-catching.

    Apple

    GitHub: GitHub, the code hosting and collaboration platform, utilizes Flexbox for many layout components, such as navigation menus, repository listings, user profiles, etc.

    GitHub

    Medium: Medium, a popular platform for publishing articles, uses Flexbox for various layout elements on its homepage and article pages.

    Medium

    Now that we have a better understanding of CSS Grid and Flexbox in detail, in the below section of this blog on CSS Grid and Flexbox, we will leave when to choose which layout for better structuring and user experience.

    CSS Grid vs Flexbox: Which to Choose and When?

    CSS Grid and Flexbox both offer their own unique ways to create flexible and responsive layouts. Having said that, they have their own set of strengths and shortcomings.

    In this section, let’s learn some of them so that you can make informed decisions when it comes to choosing the layout that best fits your needs.

    One-dimensional versus two-dimensional layout

    The most important thing you need to know about CSS Grid and Flexbox is that Flexbox is for one-dimensional layouts, and CSS Grid is for two-dimensional layouts.

    The following tweet from Rachel Andrew summarizes this difference gracefully:

    layout that only flows

    If you want a layout that only flows in one direction – either horizontal or vertical, Flexbox might be the best way to go. Flexbox is one-dimensional and is excellent for arranging elements along a single axis (either in rows or columns).

    On the other hand, if you want a layout where elements need to be arranged horizontally and vertically involving both rows and columns, a CSS Grid might be the right choice.

    CSS Grid is well suited for scenarios like this, where a design calls for items to be aligned in horizontal and vertical directions.

    To better understand this, let’s look at an example of a one-dimensional layout using Flexbox followed by a multi-dimensional layout using a CSS Grid.

    Demo: One-dimensional layout using Flexbox

    In this section, we will learn how to create a one-dimensional layout using Flexbox. As learned above, Flexbox is the best choice for arranging items in a row or column, which is a simple and efficient way to design flexible and responsive layouts.

    HTML:

    CSS:

    See the Pen
    one dimensional layout example
    by Tahera Alam (@alam_tahera)
    on CodePen.

    Result:

    navigation menu

    Code Walkthrough:

    In this example, we have a simple navigation menu (<nav> element) with three direct child elements. We are using Flexbox to arrange these elements in a horizontal row.

    flex container

    We made the nav element with the .navbar class a flex container by setting display: flex to it.

    This sets the container as a flex container, meaning the child items inside the container will be laid out according to the default flexbox layout algorithm. In a flex container, you can use properties like justify-content and align-items to control how the items are positioned along the main and cross axes, respectively.

    flex container

    We then set justify-content to space-between and align-items to center, which creates space between all three flex items and centers them vertically.

    The last item of the flex container is a <div> element with a nested <div> and a button inside it. By default, it has a display block, which makes both elements stack as columns but we want to arrange them in a row.

    justify-content

    flexbox justify-content space-between align-items center div nested div button row

    So, we used display: flex again, which arranges them in a row since the default flex-direction is a row. An important thing to note here is that Flexbox is not only great for creating a one-dimensional layout but also handy for alignment within a flex container itself.

    With this setup, we have created a horizontal navigation menu using Flexbox that is ideal for this layout because it deals with elements in one dimension, allowing us to arrange the menu items side by side easily.

    Now that we know what a one-dimensional layout looks like and how Flexbox excels in creating one, let’s move on to creating a two-dimensional layout in the section below.

    Demo: Two-dimensional layout using CSS Grid

    In this section, we will learn how to create a two-dimensional layout using CSS Grid.

    HTML:

    CSS:

    See the Pen
    grid-layout demo
    by Tahera Alam (@alam_tahera)
    on CodePen.

    Result:

    horizontal navigation menu using flexbox

    In this example, we created a two-dimensional image gallery using CSS Grid. Let’s break down the important parts.

    The element with the .grid-wrapper class is the parent container of the images. So, first, we will set display: grid to it, which tells the browser to lay out the children of this element in a grid. Next, we use the grid-gap: 15px property to specify that there should be a gap of 15px between each grid item.

    css grid gallery

    Moving on, we set the grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)) property to define the columns of the grid.

    The repeat() function tells the browser to create as many columns as necessary to fit all children but no more than the number specified in the argument. The minmax() function specifies that each column should be at least 250px wide but can be wider if necessary.

    Next, we have the grid-auto-rows: 200px property specifies the height of each row in the grid. The grid-auto-flow: dense property tells the browser to pack the grid items as tightly as possible.

    Notice how we use the .wide, .tall, and .big classes to style the images differently.

    grid layout with different sized images

    The .wide class makes the image take up two columns in the grid, while the .tall class makes the image take up two rows in the grid.

    The .big class is used to make the image even larger. It makes the image take up two columns and two rows in the grid, resulting in the largest images of the layout.

    With CSS Grid, we’ve created a multi-dimensional layout, organizing elements into rows and columns with ease. Achieving this with Flexbox would require complex CSS workarounds, as Flexbox is more suited for one-dimensional layouts. CSS Grid’s explicit grid system makes it ideal for intricate multi-dimensional layouts like this one.

    As MDN says, “A simple question to ask yourself when deciding between grid or flexbox is:

    • do I only need to control the layout by row or column – use a flexbox
    • do I need to control the layout by row and column – use a grid

    In this blog section on CSS Grid vs Flexbox, we will learn the concept of content first and layout first approaches in web design and which approach a designer or the developers choose.

    Content First vs Layout First

    When designing a website, designers or developers often face a fundamental choice: should they prioritize content or layout? The decision that will be made by either the designer or the developers significantly impacts the user experience and overall effectiveness of the website.

    Let us learn which approach a designer or a developer will choose.

    Flexbox is content-based, meaning it takes the content of the elements into account when creating the layout. This allows Flexbox to adjust the design to accommodate varying amounts of content automatically. In contrast, Grid is layout-based, focusing more on defining the overall structure of the layout rather than the content within it.

    Let’s look at a few illustrations to understand this better:

    content vs layout decision

    Intended layout

    The layout changed with increased content in the third column

    The layout changed with increased content in the third column

    the layout changed again, with more content in the third column

    The layout changed again, with more content in the third column

    Look at the above images, this is what we mean by “flexbox is content-based”.

    Unlike Flexbox, which is content-based, the grid layout system is focused on creating structured layouts with defined rows and columns. Grid requires you to specify the exact layout you want, providing precise control over the placement of elements.

    Let’s see what the previous illustrations would look like in case of a CSS Grid Layout:

    css-grid-layout-example

    The intended layout

    Increased content but still maintained the layout

    Increased content but still maintained the layout

    More content, but the layout remains the same

    More content, but the layout remains the same

    As we can see, the grid sticks to its rows and columns irrespective of the content inside them; however, Flexbox changes its layout based on the content.

    When deciding between CSS Grid vs Flexbox, it’s helpful to have a general guideline. Use CSS Grid when you have a specific layout structure in mind and need precise control. On the other hand, choose Flexbox when you prefer a more flexible approach to layout and want elements to fit naturally. It’s not always a clear-cut choice, so consider your goals and needs.

    Additionally, you can combine CSS Grid and Flexbox for complex layouts, which you will learn later in the section.

    In the below section of this blog on CSS Grid vs Flexbox, we will learn the browser compatibility that each layout offers in detail.

    Browser Compatibility

    In the modern day of web design, CSS Grid vs Flexbox are the two most used layout methods. Ensuring compatibility of these tools across different browsers and devices is crucial to delivering a consistent user experience.

    So, let’s look at the browser compatibility of Flexbox, followed by the CSS Grid.

    Compatibility of Flexbox

    CSS Flexbox layout module is widely supported across modern browsers, making it a reliable choice for creating flexible layouts. As of the latest data:

    • Global support: Flexbox uses widespread support, with a global usage of 97.7%. Unprefixed support stands at 97.53%.
    • Key supported properties: Most modern browsers support key Flexbox properties like display: flex, align-items, justify-content, and more.
    • Partial support: Some older versions of browsers offer partial support for Flexbox properties, often related to outdated specifications or syntax.
    • Exceptions: Opera 10-11.5 and Internet Explorer 6-9 do not support Flexbox. Internet Explorer 10 and 11 have partial support with certain limitations.
    • Cross-device and cross-browser compatibility: It is well-supported across mobile browsers like Chrome for Android, Safari for iOS, and Firefox for Android.

    Here’s an illustration that shows its support in detail:

    Illustration depicting the compatibility of Flexbox across various browsers and devices

    Source

    Compatibility of CSS Grid

    CSS Grid Layout enables the creation of grid-based layouts. Let’s look at a summary of the compatibility of CSS Grid:

    • Global support: It has a global usage of 95.61%, making it a widely adopted layout technique.
    • Supported properties: It supports all grid-* properties and the fractional unit (fr unit).
    • Partial support: Similar to Flexbox, some browsers offer partial support for CSS Grid in older versions, often due to adherence to previous specifications.
    • Exceptions: Chrome versions 4-28 and Firefox versions 2-39 do not support CSS Grid. However, most modern versions of these browsers provide full support.
    • Cross-device and cross-browser compatibility: It is well-supported on mobile browsers, including Chrome for Android, Safari for iOS, and Firefox for Android.

    The below illustration provides a detailed view of the support for CSS Grid:

    Illustration showing support for CSS Grid across different browsers and versions

    Source

    In the below section of this blog on CSS Grid vs Flexbox, we will learn when to use CSS Grid and Flexbox effectively for complex layouts.

    Combining CSS Grid and Flexbox – When to Use Both?

    CSS Grid and Flexbox can be used together to create complex layouts that take advantage of the strengths of both layout systems. In fact, combining both is a widely used practice, making layout creation even simpler and more efficient.

    Here are some of the cases where you might want to use both:

    • Complex header/footer structures: In many web designs, headers and footers contain elements like logos, navigation menus, social media links, and additional content.
    • CSS Grid is great for creating the overall structure of the header/footer, while Flexbox can be used inside grid items to arrange the individual elements.

      For instance, you can use CSS Grid to create rows or columns for the header/footer and then use Flexbox within those grid items to center-align navigation menus or arrange social media icons horizontally.

      illustration demonstrating combining css grid and flexbox for complex layouts

    • Card-based layouts: Card-based layouts are a common design pattern for displaying content like articles, products, prices, or user profiles. CSS Grid can help create a grid of cards with consistent spacing, while Flexbox can be applied within each card to manage content alignment, such as titles, images, and descriptions.
    • This combination allows you to maintain a uniform grid structure while fine-tuning the alignment and distribution of content within individual cards.

    card-based layouts example with css grid and flexbox

    Source

    • Sidebar with main content: When designing a website with a sidebar and main content area, CSS Grid can define the overall page structure, allocating space for both the sidebar and the main content.
    • Within the main content area, a Flexbox can be used to arrange various sections vertically or horizontally, depending on the design requirements. This mix ensures that the main content area’s internal layout is optimized using Flexbox while the broader page structure is established with CSS Grid.

    css grid and flexbox used for sidebar and main content layout

    Source

    Now that we know that combining CSS Grid and Flexbox might be a good choice, let’s build a layout using both Grid and Flexbox to solidify this knowledge.

    Here’s a sneak peek of what we are going to build:

    sneak peek of the layout we're going to build combining css grid and flexbox

    Result:

    LT Browser previewing website on various devices

    The above demo is displayed using LT Browsers, which helps you validate the website on various screen sizes. LambdaTest offers an LT Browser feature, which allows you to preview your website on a wide range of mobile devices. With more than 53 device viewports available, you can compare them side by side and synchronize interactions such as scrolling, clicking, and navigation. It provides pre-installed viewports for mobiles, tablets, desktops, and laptops.

    To start using LT Browser and test the responsiveness of your application, simply click the download button below. Once the .exe file is downloaded, run it to access all the features and capabilities of LT Browser.

    DOWNLOAD LT BROWSER 2.0 Download LT Browser

    Watch the video tutorial below to become acquainted with the features and functionalities of LT Browser.

    Subscribe to the LambdaTest YouTube Channel and get the latest updates on various automation testing tutorials covering Selenium testing, cross-device testing, Browser compatibility, and more.

    HTML:

    CSS:

    See the Pen
    Card-layout – combining CSS Grid and Flexbox
    by Tahera Alam (@alam_tahera)
    on CodePen.

    Result:

    Responsive card-based layout created using CSS Grid and Flexbox

    In this example, we created a responsive card-based layout using CSS Grid and Flexbox. Let’s break down the important parts of it.

    Code Walkthrough:

    The HTML structure consists of a grid container containing multiple grid items. Each grid item represents a card-like component containing a thumbnail image and an article with some content.

    Thumbnail image of a card-like component in a grid container

    The .grid-container class defines the grid layout, which starts as a single-column layout and switches to a two-column layout on screens wider than 500px and a four-column layout on screens wider than 850px.

    Below is the relevant code:

    The .card class represents the individual card component. The .card element is a flex container, and it has a flex-direction: column property that specifies that the flex items should be arranged in a column.

    The .card article class is also a Flexbox container for the card’s textual content, arranging the content in a column with even spacing between its elements.

    Wrapping it up!

    As web design trends evolve, layout systems like CSS Grid vs Flexbox will play a pivotal role in helping us meet the design requirements.

    In this blog, we started by discussing the basics of both CSS Grid vs Flexbox and then moved to discuss when to use a CSS Grid and a Flexbox.

    Choosing between CSS Grid vs Flexbox has no clear winner, and you need to make a pragmatic decision based on your design and project requirements. Remember, Flexbox is for layouts that need to deal with one dimension – either a row or a column and grid is for layouts that require multiple dimensions(both rows and columns).

    Another point to consider is that Flexbox is the right fit when you are flexible about layout and just want elements to fit in, while the grid is ideal when you want to focus on the layout with precise control over the position of elements.

    Frequently Asked Questions (FAQs)

    Can I use CSS Grid or Flexbox with frameworks like Bootstrap or Foundation?

    Yes, you can use CSS Grid or Flexbox alongside frameworks like Bootstrap or Foundation. These frameworks often provide grid systems that can be customized or overridden with CSS Grid or Flexbox.

    Are there any performance considerations when using CSS Grid or Flexbox?

    CSS Grid and Flexbox are highly efficient layout systems well-supported by modern browsers. However, using complex nested grids or excessive calculations in Flexbox can impact performance, so it’s best to keep layouts simple and optimized.

    What is the disadvantage of CSS Flexbox?

    Flexbox lacks support for creating complex two-dimensional layouts, as it is primarily a one-dimensional layout system.

    Does Tailwind use Flexbox or grid?

    Tailwind CSS primarily uses Flexbox for its layout system. However, it can also be used in conjunction with CSS Grid for more complex layouts.

Author Profile Author Profile Author Profile

Author’s Profile

Tahera Alam

Tahera is a front-end developer who loves developing seamless frontends and efficient backends. She has skills in React, JavaScript, Nextjs, Tailwind, MongoDB, Solidity, and more. She loves to learn new technologies and finds writing about them to be a great way to share knowledge with others. In her free time, she enjoys reading thrillers and engaging with the tech community on Twitter.

Blogs: 11



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free