Center Anything with Flexbox
Centering a child horizontally and vertically used to require pixel math, table tricks, or absolute-positioning hacks. Flexbox collapses the whole thing into three properties. This snippet covers the canonical centering pattern, the inline-flex variant for centering inside button-shaped wrappers, and the gap-aware multi-child version that keeps spacing consistent.
258 views
5
.center {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}display: flex turns the container into a flex parent, align-items: center centers the cross axis (vertical, by default), and justify-content: center centers the main axis (horizontal). The min-height: 100vh makes the container at least the viewport tall so the centering has room to work; for non-fullscreen wrappers, swap it for an explicit height. This is the three-line incantation that replaced a decade of hacks for centering modals, splash screens, and empty states.
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
border-radius: 0.375rem;
background: hsl(220 90% 56%);
color: white;
}inline-flex keeps the container itself flowing with surrounding text (so a centered button sits next to inline labels) while the children get the same alignment behaviour as full flex. Adding gap is the one-line replacement for margin-right between an icon and its label, and it removes the awkward trailing space on the last child. This is the pattern most design systems use for buttons, chips, and tag pills.
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.75rem 1rem;
}
.toolbar > .group {
display: flex;
align-items: center;
gap: 0.5rem;
}Toolbars and headers usually have two or three groups separated by space: brand on the left, search in the middle, actions on the right. justify-content: space-between pushes the groups apart without nested wrappers, and the inner .group rule keeps icons aligned to their labels. The outer gap stops things from touching even when there is no extra space. This shape generalises to any horizontal bar where the slots have different content widths.
