DEV Community

Toshita Singh 💜
Toshita Singh 💜

Posted on

Better way to make equal sized columns using flexbox?

Is there a better way than the following to make equal sized columns no matter the content size using flexbox?

ul {
  display: flex;
}

li {
  flex-basis: 30%;
  flex-grow: 1;
}
Enter fullscreen mode Exit fullscreen mode

Image description

Challenge link (Layout two): https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox_skills

Top comments (2)

Collapse
 
dianale profile image
Diana Le • Edited

Flex-basis is probably one of the most confusing CSS properties (in combination with the flex-grow and flex-shrink), and if what you really want is 3 equal-width columns no matter what the content, then you are better off using grid instead of flexbox. However if you need to use flex, you can do:

ul {
  display: flex;
}
/* flex-grow: 1; flex-shrink: 1; flex-basis: 0 */
li {
   flex: 1 1 0;
}
Enter fullscreen mode Exit fullscreen mode

See developer.mozilla.org/en-US/docs/W... for more information.

You could also force a width. The default flex-basis value is auto, which means it checks for a width set, and since we're setting the width to 33%, that becomes the default flex-basis of the li tag:

ul {
  display: flex;
}
li {
   width: 33.33333333%;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

There are two different ways to reach what you expect,
1- Let the flex items to rearrange itself.
2- Defining the width yourself (with or without a calc).

The flex property is a shorthand property for the flex-grow, flex-shrink, and flex-basis properties.

Live example + code:

Hope it helps 😁

Once you understand Flex you'll find flex suitable for creating almost any piece of your UI. I personally prefer Flex to Grid.