CSS Grid Vs CSS Flexbox-Which one to use?

Gilbert Cheruiyot
3 min readJan 16, 2023

--

A snippet showing CSS in use

When I started out on CSS, I initially had a difficulty mastering and exploiting the full potential of Flexbox and Grid to achieve high quality layouts for my websites. In this article, I discuss how the concepts of flexbox and grid could be used to create visually appealing websites.

CSS Grid and Flexbox are both layout modules in CSS that allow you to control the positioning and alignment of elements on a web page. Both have their own strengths and use cases, and choosing between them often comes down to the specific requirements of your project.

CSS Grid is a two-dimensional layout system that allows you to create rows and columns in your layout. It is best suited for larger, more complex layouts, such as those found in web applications or landing pages. With CSS Grid, you can easily define the number of rows and columns in your layout, and then position elements within those rows and columns.

Here’s an example of how to create a simple grid layout using CSS Grid:

.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 100px);
}
.grid-item {
grid-column: 1 / 2;
grid-row: 1 / 2;
}

In this example, we have created a grid container with 3 columns and 3 rows. Each column and row is set to take up 1 fraction of the available space (1fr) and 100px, respectively. We have also defined a grid item and positioned it in the first row and first column of the grid.

On the other hand, Flexbox is a one-dimensional layout system that allows you to control the alignment and distribution of elements in a single dimension, either horizontally or vertically. It is best suited for smaller, simpler layouts, such as those found in navigation bars or lists. With Flexbox, you can easily align elements to the start, end, or center of their container, and distribute them evenly.

Here’s an example of how to create a simple flex layout using Flexbox:

.flex-container {
display: flex;
justify-content: center;
align-items: center;
}
.flex-item {
flex: 1;
}

In this example, we have created a flex container and set the justify-content property to center, which aligns the flex items horizontally within the container. The align-items property is set to center, which aligns the flex items vertically within the container. We have also defined a flex item with a flex value of 1, which means it will take up 1 unit of the available space.

In summary, CSS Grid is best for larger, more complex layouts, while Flexbox is best for smaller, simpler layouts. The choice between the two often comes down to the specific requirements of your project. It’s also worth noting that both CSS Grid and Flexbox can be used together, so you can take advantage of the strengths of both for your layout.

--

--

Gilbert Cheruiyot

Tech Alchemist: Crafting Code, Guiding Minds, and Spinning Stories