There was a time that positioning elements with CSS could be a real hassle, depending on what was needed to do.
Then, Flexbox came to the rescue, facilitating element positioning. But it didn’t take long to browsers adapt and start supporting CSS Grid.
This left us with a question: Flexbox or Grid?
A common mistake is thinking that Grid was intended to replace Flexbox, since most browsers now support Grid. Such thought couldn’t be more wrong.
You need to take into account that:
We can surely use flexbox to work with two-dimensional elements, but this tool is far more used when facing an one-dimensional element, be it a line or column.
A menu is always a good example of that (no matter if it is vertical or horizontal).
Grid is perfectly capable of working with a one-dimensional element, but it shines when dealing with two-dimensional elements.
Defining your page structure with Grid will be a piece of cake compared to Flexbox.
You can set the start and end of an element in your grid, which gives you a lot of flexibility (I know, ironic right?). You can also name areas inside your grid structure to further indicate to an element that it belongs there. This can make your code more readable and easy to maintain.
If you already know how many rows and columns you’ll need, then Grid is probably more suited for you than Flexbox in such a case.
Beyond that, is possible that you’ll write fewer media queries, since you can use functionalities like
auto layout
, minmax()
, repeat()
and auto-fill
.It’s always better to enjoy the best of both worlds, right?
This is what happened in the example above:
With further understanding, you’ll realize that, depending on the situation, one option can be better, but using the other isn’t wrong.
Nothing blocks you from eating with forks and knives, but knowing how to use both together can make your life a lot easier.
As you get more experienced with Flexbox and Grid, you’ll choose more intuitively the best option for each case.