Let’s face it, CSS grid and CSS flex are an awesome addition to CSS layouts and they make development very flexible so to speak. But that is not why you are here, you are here to know when to use either of the two.
Well, first things first, do you understand the difference between CSS grid and CSS flex? If not, then it is best we first get to clear the air on this with a quick refresher.
CSS grid is a two dimensional approach of envisioning the container element. This element can be a div for example for the root your HTML element or any other part of your HTML.
What CSS grid does is that it divides your container into a series of rows and columns. This results to some form of a grid and hence the name.
CSS flex is a uni-dimensional approach to working with the container element. With a CSS flex, you either choose to work on the row (horizontal axis) or column (vertical axis) of the container element.
In short, you can work with one of either row or column and not with both.
Now, this depends on your needs. That is all that can be said honestly. These two CSS layouts will be good in some cases, and in some cases, just not feasible or a mere overkill.
The reason why this is the case, let’s look at an example of when you can use either.
For example, you can use a CSS grid when you want to create a responsive HTML website. Yes! Well, how is this possible? Remember that CSS grid divides a page into a series of rows and columns?
Now, with CSS media queries, you can be able to place content on the right grid, depending on the specific CSS media queries breakpoints specified on your CSS.
A classic example of when to use CSS flex is when you want to make the container contents behave in a flexible manner, like with different screen sizes.
NOTICE that here, the contents either behave depending on the axis your CSS flex container is targeting.
This makes it possible to resize container elements in a smooth way with varying screen sizes.
As you can see, CSS grid and CSS flex have their own use cases, and each performs best in a given scenario than the other.
At times, it may be an overkill to use CSS grid when you would have just used a CSS flex.
So, you need to decide your use case and then go with the right option between CSS grid and CSS flex that best fits your use case.
Now that you have the hang of how CSS grid and CSS flex work, it is possible to decide when you should use either.
With that, until the next one.