Flexbox (flexible box layout) is a one-dimensional, responsive layout system, designed for arranging elements in a single row or column.

In flexbox, you have the flex container that holds flex items.

Flexbox has a main axis (the direction of flex items) and a cross axis. Flexbox defaults to row layout and so the default axis is left-to-right.

Flex items can grow or shrink based on available space using properties like flex-grow and flex-shrink.

  • display: flex enables flexbox layout on an element.
  • flex-direction specifies the direction of the main axis: row, row-reverse, column, or column-reverse.
  • justify-content aligns flex items along the main axis.
    • Common values: flex-startcenterflex-endspace-between, & space-around.
  • align-items aligns flex items along the cross axis.
    • Common values: flex-start, center, flex-end, & stretch.
  • flex-wrap specifies whether items should wrap to the next line if there’s not enough space.
    • Use flex-wrap: wrap to allow items to wrap to the next line.
  • flex is shorthand for flex-grow, flex-shrink, and flex-basis.
    • flex: 1; equates to flex: 1 1 0 and makes items grow along the main axis to fill the available space proportionally.
  • flex-grow determines how much an item can grow relative to other items if there’s extra space in the container. (Most common values are 0 and 1.)
    • Setting to a high value (e.g. 10) can cause unexpected or disproportionate behavior.
  • flex-shrink determines how much a flex item can shrink relative to other flex items if there’s not enough space. (Most common values are 0 and 1. Default is 1.)
    • Setting to a high value (e.g. 10) can cause unexpected or disproportionate behavior.
  • flex-basis sets the initial size of a flex item before any growing or shrinking occurs.
    • Accepts pixels, percentages or auto. auto means the item’s initial size will be based on its content size.
    • If you want to use width or height, consider setting flex-basis to auto or 0.
  • gap adds space between items, similar to adding margin to the items.
    • It’s a new property so doesn’t show up in many resources yet but is reliable.

Flexbox FAQ

  • How do you center an element horizontally? To center an element horizontally, you can use margin: 0 auto; or display: flex; justify-content: center; on the parent element.