Layout

flex

flex is a shorthand for how a flex item grows (flex-grow), shrinks (flex-shrink), and what size it starts from (flex-basis). A common use is flex: 1, which makes items share the leftover space.

Syntax

none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]

Preview

1234
Presets
Sample
Items
Drag the bottom-right corner to resize

Shorthand breakdown

flex
1flex-grow
1flex-shrink
0%flex-basis

Code

.box {
  display: flex;
}

.box > :nth-child(2) {
  flex: 1;
}

Controls

flex1
flex
flex-grow1
flex-shrink1
flex-basis0%
1234

About

Writing the value

  • none: the same as 0 0 auto. The item neither grows nor shrinks and keeps its own size.
  • auto: the same as 1 1 auto. The item starts from the size set by its content or width, and both grows and shrinks.
  • With numbers, write the grow factor, the shrink factor, and the starting size, in that order. The starting size may also come before the factors. A number without a unit is read as a factor, so write a zero starting size with a unit, as 0px or 0% (only a 0 after two factors is the starting size).
  • Parts you leave out are not the initial values of the properties: flex-grow and flex-shrink become 1, and flex-basis becomes 0%. So flex: 1 is 1 1 0%, and flex: 200px is 1 1 200px.
  • Without flex, the properties keep their initial values, 0 1 auto: the item does not grow, and shrinks only when the items overflow.

The preview makes the box display: flex with a helper declaration and writes flex only on the second item.

When to use it

  • flex: 1: starts every item from 0% and then shares the leftover space, so items with flex: 1 get equal widths however much content they hold.
  • flex: auto: starts from the size of the content and shares what is left, so items with more content end up wider.
  • flex: none: for icons, buttons, and other items that should keep their size when their neighbors push on them.

Watch out

  • While overflow is visible, a flex item does not shrink below its content, because of the initial min-width: auto (min-height when the items run vertically). If items with flex: 1 still differ in width because of a long word or URL, add min-width: 0 to them.
  • Being a shorthand, flex overwrites all three of flex-grow, flex-shrink, and flex-basis. A flex-basis written earlier is replaced by the value for a left-out part, such as 0%.

Comments