Code Snippets
/

Center Anything with Flexbox

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.

CSS
Easy
3 snippets
css-selectors
css-flexbox
css-alignment
code-template

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.