CSS Flexbox Tutorial: Align Items in a Row or Column
Flexbox lays out items along one axis, a row or a column, and makes it easy to space and align them. Navigation bars, button groups, card footers and "push this to the right" problems are all Flexbox jobs.
Turning it on
display: flex on a parent turns it into a flex container, and its direct children become flex items. By default they line up in a row, shrink if they do not fit, and stretch to the same height.
The two axes
flex-directionpicks the main axis:row(the default),row-reverse,columnorcolumn-reverse.justify-contentdistributes items along the main axis:flex-start,center,flex-end,space-between(first item at the start, last at the end, equal gaps between) orspace-around.align-itemsaligns items on the cross axis, the perpendicular one:stretch(default),flex-start,center,flex-endorbaseline.
Perfect centering is two lines: justify-content: center; align-items: center;.
Space and wrapping
gap: 1rem puts space between items without adding any to the outer edges, which beats juggling margins. flex-wrap: wrap lets items move to a new line instead of shrinking when space runs out.
Growing and shrinking
Each item has three sizing values, usually set with the flex shorthand:
flex-grow: how much of the leftover space the item takes (0 means none).flex-shrink: how much it gives up when space is short.flex-basis: its starting size before growing or shrinking.
flex: 1 is shorthand for "grow 1, shrink 1, basis 0", so several flex: 1 items share the row equally. In the example, a 600-pixel row contains a fixed 100-pixel logo and two items with flex: 1 and flex: 2, separated by 20-pixel gaps. The script prints each item's rendered width.
Expected page text
Logo flex 1 flex 2 logo: 100px flex 1: 153px flex 2: 307px
The free space after the logo and the two gaps is 600 - 100 - 40 = 460 pixels. It is split one part to two, so the items get roughly 153 and 307 pixels, as the output shows.
Common mistakes
- Putting
display: flexon the item instead of its parent. The container is the element whose children you want to arrange. - Using
justify-contentto center vertically in a row. In a row, vertical is the cross axis, so usealign-items. - Expecting
gapto work in very old browsers; every current browser supports it in Flexbox.
Summary
display: flexon the parent; children become flex items in a row.justify-contentworks on the main axis,align-itemson the cross axis.gapspaces items;flexcontrols how they share space.
Quiz: Flexbox