Defining dimensions on flexbox children using flex-basis

Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 4 years ago

The flex-basis property allows us to define the dimension (along the flex-direction axis) that a flexbox child should ideally have.

[00:00] The most flexible part of flexbox is the sizing. We use three properties to handle the resizing of flexbox children along the flex-direction, flex-grow, flex-shrink, and flex-basis, which are all applied to individual flex children and not to the flex container. Let's start with flex-basis.

[00:16] With flex-basis, you can define the optimal size of a child along the flex-direction. Let me explain what that means with an example. In this example, I have three h1 tags with different background colors to make then distinguishable. I can set display to flex on the parent container. In this case, it's the body tag.

[00:33] Notice that even though h1s are block tags that usually have a default width set to 100 percent, they shrink down to the content width here. Let's dig into the complexity of how the width is determined. If I set a width on this first child to 200 pixels, it will respect that width.

[00:49] But if I set the flex-basis to 150, it will override the set width, but it will not exceed the max width or go under the min width. In essence, what is happening here is a cascading hierarchy. If flex-basis is not set, it defaults to auto, which means look at the dimension corresponding to the flex-direction.

[01:07] Since our flex-direction here is row, the corresponding dimension is width. If width is not set, it defaults to the content width of the element, which in this case is just the size of the word.

[01:17] Because of the complexity this hierarchy can introduce, I recommend sticking with flex-basis, not setting a width for all flexbox children in row flex-direction or height for all column flex-direction children. It makes it easier to know where your dimension is being set. Flex-basis is the ideal size for the element along the flex-direction if it has enough room.

Rodrigo
Rodrigo
~ 9 years ago

Hi Garth, what do you mean when you say "If is has enough room" at the end of this lesson?

Thanks!

Garth Braithwaite
Garth Braithwaiteinstructor
~ 9 years ago

When setting the flex-basis will fill the available space until it hits that value, if it cannot hit that value it will just fill the available space.

I made an example https://jsbin.com/gocovoluge/edit?html,css,output

Markdown supported.
Become a member to join the discussionEnroll Today