Sub topic 8
Starting size with flex-basis
This chapter assumes you can create a flex container with display: flex, know the main axis and cross axis, and understand width, rem and percentages. Here you will learn what flex-basis does and how it differs from width.
What flex-basis does
flex-basis sets an item's starting size along the main axis. Flexbox computes this size first. Then flex-grow and flex-shrink add or remove space from it.
The main axis depends on flex-direction. In a row, flex-basis acts like a width. In a column, it acts like a height.
.card {
flex-basis: 200px;
}How the browser picks the starting size
The browser follows these steps for each item:
- If
flex-basisis a length or a percentage, it uses that value. - If
flex-basisisauto(the default), it uses the item'swidth(orheightin a column). - If that is also
auto, it usescontent, which is the item's natural size based on what is inside it.
The value content can also be written on its own, but auto is more widely used and gives the same result when no width is set.
flex-basis versus width
If both are set, flex-basis wins on the main axis. The width is ignored for the starting size.
.box {
width: 100px;
flex-basis: 300px;
}In a row container, this item starts at 300px, not 100px. Using flex-basis is clearer because it also works when you switch to flex-direction: column, where you would otherwise need height.
Two limits still apply after the starting size is chosen. min-width and max-width can clamp the final size. Items may also grow or shrink away from the basis.
A worked example
.row {
display: flex;
width: 600px;
}
.a { flex-basis: 100px; }
.b { flex-basis: 200px; }
.c { flex-basis: 100px; }The bases add up to 400px. The container is 600px, so 200px is free. With the default flex-grow: 0, nothing grows, and the free space stays empty at the end of the row. The next chapter covers flex-grow, which shares that space.
Common errors
- Expecting an exact size.
flex-basisis a starting point. With the defaultflex-shrink: 1, items can shrink if the row is too narrow. - Using a percentage in a container with no set size. A percentage basis refers to the container's size. If that size depends on its content, the result can be unpredictable.
- Setting
flex-basis: 0and expecting no width. The item's minimum content size can still stop it from shrinking that far.
Exercise
A row flex container has an item with width: 150px; flex-basis: 250px;. What is the item's starting size, and why?
Show answer
250px. On the main axis, a flex-basis value other than auto takes priority over width, so the width of 150px is ignored when computing the starting size.
Exercise
An item has flex-basis: auto and no width. Where does its starting size come from?
Show answer
From its content. When both flex-basis and width are auto, the browser uses the item's natural content size.