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

BasicDemo.tsx

import React from "react";
export default function BasicDemo() {
return (
<div
style={{
display: "flex",
flexWrap: "wrap",
width: "200px",
height: "200px",
}}
>
<div
style={{ width: "100px", height: "100px", backgroundColor: "#ccc" }}
></div>
<div
style={{ width: "100px", height: "100px", backgroundColor: "#eee" }}
></div>
<div
style={{ width: "100px", height: "100px", backgroundColor: "#eee" }}
></div>
<div
style={{ width: "100px", height: "100px", backgroundColor: "#ccc" }}
></div>
</div>
);
}

Expanding Further

You can expand this trick further to create m x n grids with flexbox alone.

More Demo

AdvancedDemo.tsx

import React from "react";
export default function AdvancedDemo() {
const [columns, setColumns] = React.useState(2);
const [rows, setRows] = React.useState(2);
return (
<>
<div
style={{
display: "flex",
flexWrap: "wrap",
width: columns * 100,
height: rows * 100,
}}
>
{[...Array(rows * columns)].map((_, i) => {
return (
<div
key={i}
style={{ width: 100, height: 100, border: "1px solid #ccc" }}
></div>
);
})}
</div>
<label>
Number of columns
<input
type="range"
min={1}
max={5}
value={columns}
onChange={(e) => setColumns(Number(e.target.value))}
/>
</label>
<label>
Number of rows
<input
type="range"
min={1}
max={5}
value={rows}
onChange={(e) => setRows(Number(e.target.value))}
/>
</label>
</>
);
}

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. 🙃