This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Defining dimensions on flexbox children using flex-basis

1:38 CSS lesson by

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

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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

Avatar
Rodrigo

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

Thanks!

Avatar
Garth

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

In reply to Rodrigo

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.

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.

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.

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.

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?