CSSEasy
What are the ways to center an element on both axes?
By FrontendPro Editorial Team Updated 8/14/2026
#css#layout#flexbox#grid
Answer
css
/* 1. Grid - shortest */
.parent { display: grid; place-items: center; }
/* 2. Flex */
.parent { display: flex; align-items: center; justify-content: center; }
/* 3. Absolute + transform (when the child is out of flow) */
.parent { position: relative; }
.child { position: absolute; inset: 50% auto auto 50%; transform: translate(-50%, -50%); }
/* 4. Horizontal only, for a block with a width */
.child { margin-inline: auto; }
Note: options 1 and 2 need the parent to have a height (e.g. min-height: 100dvh) for vertical centering to be visible.
