Equal Size Columns with CSS Grid
When creating a set of equal size columns in CSS for an unknown number of items, you might first reach for flexbox to solve the problem. However, there are actually quite a lot of gotchas when using flexbox, but CSS grid makes this super simple.
A typical approach with flexbox might look something like this:
div {
display: flex;
}
div > * {
flex: 1;
}
In some cases, this will do what we want, but it’s not guaranteed to always
give us equal width columns, as it’s dependent on the children of the flex
container. Instead we can use CSS grid and get equal widths no matter what.
The secret is grid-auto-flow
:
div {
display: grid;
grid-auto-flow: column;
grid-auto-columns: 1fr;
}
To learn more, checkout this great article by CSS tricks that goes in much more depth on this subject.