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: flexenables flexbox layout on an element.flex-directionspecifies the direction of the main axis:row,row-reverse,column, orcolumn-reverse.justify-contentaligns flex items along the main axis.- Common values:
flex-start,center,flex-end,space-between, &space-around.
- Common values:
align-itemsaligns flex items along the cross axis.- Common values:
flex-start,center,flex-end, &stretch.
- Common values:
flex-wrapspecifies whether items should wrap to the next line if there’s not enough space.- Use
flex-wrap: wrapto allow items to wrap to the next line.
- Use
flexis shorthand forflex-grow,flex-shrink, andflex-basis.flex: 1;equates toflex: 1 1 0and makes items grow along the main axis to fill the available space proportionally.
flex-growdetermines 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-shrinkdetermines 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-basissets the initial size of a flex item before any growing or shrinking occurs.- Accepts pixels, percentages or
auto.automeans the item’s initial size will be based on its content size. - If you want to use
widthorheight, consider settingflex-basisto auto or 0.
- Accepts pixels, percentages or
gapadds 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;ordisplay: flex; justify-content: center;on the parent element.