https://www.reddit.com/r/csshelp/comments/1hzkph6/flexbox_the_difference_in_behavior_when_using/
created by Mother-Anteater-3725 on 12/01/2025 at 11:24 UTC
2 upvotes, 1 top-level comments (showing 1)
Hello everyone, I'm taking the Odin project as a course of learning web dev and I'm currently working with `flexbox` precisely direction, so I was looking at the following case: I have a div with three sub div and I applied the following CSS code
`.flex-container{ display: flex;`
`/* flex-direction: column; */ }`
`.flex-container div {`
`background: peachpuff;`
`border: 4px solid brown;`
`height: 80px;`
`flex: 1; }` which works fine horizontally, so I wanted to switch to vertical, my first intuition was to set the direction to column and then the width to 80 instead of Height, But it didn't work I tried to find an explanation but I couldn't, and the solution is to set the `flex-basis` to `auto` in the `div` element, anyone to help me get my head around this
Comment by utsav_0 at 16/01/2025 at 02:18 UTC
1 upvotes, 0 direct replies
So, here's the thing:
By default, all the block level elements, cover 100% width, so .flex-container here covers 100vw.
Then you set the flex items (four inner divs) height to 80px, and for width, you set flex-grow to 1. Which means, grow to cover flex container completely (100vw in this case).
Thus, they grow equally and takes 1/3 of the container each. So far, so good.
But then you change the flex-direction to column, and width to 80px. Here, what's the height of block level elements by default? auto.
Which in this scenario mean, only keep the height of the .flex-container enough so it fits all the flex items (they have no height, so zero).
So, even though, you also have flex-grow set 1 here, but it simply means grows all elements such that they cover the complete height of the container (which is zero).
So, the solutions?
You can simply set a height for the flex-container.
Or you can set a fixed height to the flex-items (but if you use the flex shorthand, it resets that height as it also takes the value flex-basis, which is equivalent to height in this case. So, either set flex-grow directly without the shorthand, or also set the flex-basis in the shorthand itself like flex: 1 80px).