I’m trying to use Flexbox to get a 3 by 3 grid of elements.
Here’s what I have:
export default function App() {
return (
<div
style={{
display: "flex",
flexWrap: "wrap"
}}
>
{Array.from({ length: 9 }, (_, index) => (
<div
style={{
flex: 1,
height: 200,
backgroundColor: "gray",
margin: 4,
width: 150
}}
/>
))}
</div>
);
}
This renders the following:
However, this is what I would like to do:
What am I doing wrong here? I have to use Flexbox, I can’t use Grid, and I’ve tried to make use of flex-wrap
, but it doesn’t seem to work, even if I specify a value for the width of a card.
2
Answers
Using the CSS Grid for this purpose will be much easier, but if you want to stick with the flexbox approach for any reason, you can follow the following approach.
The most vital thing about the CSS Flexbox is the flex property. The flex property stands for
flex-grow
,flex-shrink
, andflex-basis
.For your purpose, you should set the flex property in a way that allows three elements in a row, so we will do as follows:
flex-grow
to1
to let each item in a row grow equally.flex-shrink
to0
to prevent each item from shrinking when insufficient space exists.flex-basis
to33.3333%
as we need three equal columns in each row. Also, if we need a gap between these elements, we have set the gap within theflex-basis
property. Remember that if each element has a margin, the desired gap should be twice the margin. So for the5px
margin, we need a10px
gap and the final result forflex-basis
will becalc(33.3333% - 10px)
.As an example, you can do something like the below:
Important note: One crucial property to make this happen is
box-sizing
; we need to set its value toborder-box
. Theborder-box
value will:NOTE: You can learn more about CSS flexbox in CSS tricks website.
Your current code sets up a Flexbox container with elements displayed in a row with flexWrap: "wrap", but to achieve a 3 by 3 grid, you need to make a few adjustments. Here’s how you can modify your code:
In the modified code:
These changes should give you a 3 by 3 grid of elements using Flexbox. You can adjust the width and other styles to match your design requirements.