CSS flexbox: one-dimensional layouts
In short: Flexbox arranges elements in a row or column, distributes free space and aligns them. It is the standard tool for menus, card rows and centred content.
In more detail: You turn a container into a “flex box” with display: flex. Its direct children become flex items and follow the container’s rules.
In Depth
- Main axis:
flex-direction: row(default) orcolumn. The cross axis is perpendicular to it. - Aligning:
justify-contentdistributes along the main axis (flex-start,center,space-between,space-around).align-itemsaligns across (stretch,center,flex-start). - Spacing:
gap: 1remsets gaps without margin tricks. - Wrapping:
flex-wrap: wraplets items wrap onto the next line. - Growing and shrinking:
flex: 1lets an item fill free space,flex: 0 0 200pxgives a fixed width. Written out:flex-grow,flex-shrink,flex-basis. - Centring:
display:flex; justify-content:center; align-items:center;centres a child horizontally and vertically. - When Grid? For two-dimensional grids (rows and columns at once) CSS Grid is better. Flexbox is meant for one direction.
See also: CSS, media queries