Flexbox handles navbars, toolbars, centering and card rows: most one-dimensional layout on the web.
display: flex turns an element into a flex container and its direct children into flex items, laid out along one axis.
flex-direction: row(default) orcolumnsets the main axis. The other is the cross axis.justify-contentdistributes items along the main axis:flex-start,center,space-between,space-around,space-evenly.align-itemsaligns them on the cross axis:stretch(default, equal heights),center,flex-start,baseline.gap: 1remputs space between items without margin tricks.flex-wrap: wraplets items wrap onto new lines instead of shrinking.
Each item's size is controlled with the flex shorthand, flex: grow shrink basis:
flex: 1means grow to share free space equally (basis 0).flex: nonekeeps the content size, neither growing nor shrinking.flex: 0 0 200pxmakes a fixed 200px column.
Two classic patterns: perfect centering with display: flex; justify-content: center; align-items: center, and pushing one item to the far end with margin-left: auto, since auto margins absorb free space.
Remember that justify-content works on the main axis, so it becomes vertical when flex-direction: column. And flexbox is one-dimensional: when you need rows and columns to line up, use grid.
Example
/* <header class="bar"><a>Logo</a><nav>...</nav><button>Sign in</button></header> */
.bar {
display: flex;
align-items: center; /* vertical centering in a row */
gap: 1rem;
padding: 0.5rem 1rem;
}
.bar button { margin-left: auto; } /* pushes the button to the far right */
.center { /* center anything both ways */
display: flex; justify-content: center; align-items: center;
min-height: 50vh;
}
.cards { display: flex; flex-wrap: wrap; gap: 1rem; }
.cards > * { flex: 1 1 250px; } /* at least ~250px, grow to fill each row */
.sidebar-layout { display: flex; }
.sidebar-layout aside { flex: 0 0 240px; } /* fixed */
.sidebar-layout main { flex: 1; } /* takes the rest */Remember
- justify-content = main axis, align-items = cross axis
- gap spaces items; flex-wrap allows new lines
- flex: 1 shares free space; flex: none keeps content size
- margin-left: auto pushes an item to the end
Watch out for
- Expecting justify-content to center vertically in a flex-direction: column container; there it's align-items for horizontal.