๐ŸŽ“ A1Learner
๐Ÿ”

CSS Flex Items

Flex item properties size and reorder single items inside a flex container. flex-grow gives an item a share of the spare space, and order moves an item along the row.

A bigger share for one item

Every item grows by one share. The first item grows by two shares, so it ends up wider.

ul {
  display: flex;
  width: 500px;
}
li {
  flex-grow: 1;
}
li:first-child {
  flex-grow: 2;
}

A starting size for items

flex-basis sets the size each item starts from. Three items at 150 pixels leave spare room in the 500 pixel row.

ul {
  display: flex;
  width: 500px;
}
li {
  flex-basis: 150px;
}

Move an item with order

A negative order value pulls the last item to the front of the row. The HTML stays untouched.

ul {
  display: flex;
}
li:last-child {
  order: -1;
}

Example

ul {
  display: flex;
  width: 500px;
}
li {
  flex-grow: 1;
}
li:first-child {
  flex-grow: 2;
}
li:last-child {
  order: -1;
}

Key points

  • flex-grow: sets an item's share of the spare space
  • flex-basis: sets an item's starting size before space is shared
  • flex-shrink: lets an item give space back when the row is too full
  • flex-shrink has a default value of 1
  • The flex shorthand sets grow, shrink and basis in one declaration
  • order changes the visual order only, and the HTML order stays the same

In this example, the list becomes a flex row with a fixed width. Every item grows by one share of the spare space. The first item grows by two shares instead. The last item has order minus one, so it appears first in the row.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does flex-grow control?