How flex-item size are calculated when its width is given?

I have read a lot about flex box and have understood most of the part. However, there is one thing that I am not able to figure is that in case we have more than 1 flex-item inside a flex container, how their final width is calculated when one of them is declared its width that is greater/less than its parent container size. Here is the link to the pen I have written to experiment with flex: https://codepen.io/anurag1989/pen/yLRqPwO
1 Reply
Joao
Joao2y ago
I suspect that the key to fully understand how it works is with the default values of the flex property, which is really a shorthand for another three properties: flex-grow, flex-shrink and flex-basis. https://developer.mozilla.org/en-US/docs/Web/CSS/flex#values For example without any width specified on any element you can see that the wrapper allows for more space for each child element, that remains unused because by default flex items only take up as much space as needed. When you specify a width on a child, they'll adjust to that width. The flex container by default behaves like block element. It will respect it's width property, but you can also use display: inline-flex to make it wrap around it's children immediately instead of behaving like a block. With this property it will shrink and grow as needed, but as mentioned giving it a fixed width will make it so that it won't shrink or grow at all. When this happens, since the parent won't resize, then it's children will have to and that's when you start looking at those flex properties. By default all flex items will shrink to their minimum size but will not grow to take any remaining space. After all elements know their minimum value, other elements that have some width assign can then work out whether they fit in that remaining space using the full width they are given, or need to shrink. If all flex items have the same width assigned, and the total width is greater than the container, they will use the same space, although based on other properties like font size, borders, padding, etc that space assigned may actually end up being different. This is where properties like box-sizing: border-box can have a noticeable effect. The exact order of computations that the browser makes to calculate this, or which properties take precedence over which ones, that I don't know. I modified the codepen slightly and included a label to see the actual size of each box. For some reason it won't work properly with Codepen's auto-updateing so go to Settings > Behavior and turn off "Auto-Updating Preview". https://codepen.io/D10f/pen/GRYBXNa For example you can see that box2 gets more space than box3 even when assigned the same width, because of the wrapping of their text content. Or rather, sometimes depending on if the width just so happens to allow for that wrapping.
Want results from more Discord servers?
Add your server