3

I need some basic help with flexbox. The question has probably been asked, but I couldn't find it anywhere.

I have a container div set to display: flex; with an unknown amount of children, like so:

<div class="container">
 <div class="child">First child</div>
 <div class="child">Second child</div>
     ...
 <div class="child">Nth child</div>
</div>

Now, I need every child to have the same width. In order to do that, I was thinking to use flex: 0 0 ?. My question is what should I replace ? with ? In an ideal world, I would set :

flex: 0 0 calc(100/n)%;

where n would be the amount of children. The thing is, I don't know n (how many children <div class="container"> has) in advance.

PS: I'm developing an interface in ReactJS. I've only shown HMTL code for better readability. All solutions are welcome, but CSS-only are preferred to ReactJS ones.

sleepydrmike
  • 111
  • 1
  • 9

2 Answers2

4

How about this:

#container {
  display: flex;
  border: 4px solid black;
  padding: 3px;
  width: 600px;
}

.box {
  flex: 1 1 0px;
  border: 2px solid grey;
  padding: 2px;
}
<div id="container">
  <div class="box">We choose to go to the Moon...We choose to go to the Moon in this decade and do the other things, not because they are easy, but because they are hard.</div>
  <div class="box">Hello World</div>
  <div class="box"></div>
  <div class="box">Never Gonna Give You Up, Never Gonna Let You Down</div>
 </div>

flex: 1 1 0px is shorthand for:

flex-grow: 1;
flex-shrink: 1;
flex-basis: 0px;

The flex-basis sets them all to be the same initial width of nothing, then the equal amounts of flex-grow+flex-shrink cause them to expand to the same width, regardless of the contents.

Robson
  • 2,008
  • 2
  • 7
  • 26
1

I think flex-grow: 1 is all you need to let all children grow equally to take up the available space.

If you want to use the shorthand flex:, you can skip the last property(basis). That will give it the value auto, and it will have the same effect as long as flex-grow is set to 1.

.parent{
display:flex;
flex-direction: row;
background: green;
}
.parent div{
background: yellow;
flex-grow: 1;

/*flex:1 0;*/
}
<div class="parent">
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
<div>A</div>
</div>
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • I tried this, but It doesn't work. Replace all your `A`'s by words of different lengths. The `flex-grow` property will distribute _remaining space_, not the actual width of the child. At least it's what happened when I tried it. – sleepydrmike Aug 31 '21 at 17:14