How to Create a 2x2 Grid with Flexbox
For context, I was asked this question during a TikTok frontend interview, and I initially thought it was a trick question.
I replied it was not possible with flexbox and that it was only possible with CSS Grid.
After the interview, I was curious and decided to do a quick google. And it turns out it is actually possible with flexbox.
The Solution
The solution to this trick question is to use the flex-wrap
property.
If you are not familiar with the flex-wrap
property, it is used to wrap items to the next row or column when the items
exceed the container's width or height.
Demo in Action
Expanding Further
You can expand this trick further to create m x n grids
with flexbox alone.
More Demo
However, I would advise against this because the CSS Grid was specifically created for this use case and is much more intuitive to use.
Do not try to use this flexbox trick in production or in a large project, because it is unintuitive and personally I feel it is
a hacky solution.
If an interviewer asks you this question, I think the best reply would be to try to convince him that CSS Grid is the best option forward while being as polite as you can.
I hope that after you have read this blogpost, you would be prepared to face this terrible and unpractical question in your next frontend interview. 🙃