dev3 ·
I have a card inside a full height container and I want it centered both ways. I have seen margin auto, absolute with transforms, flexbox and grid. Which one should I use today?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
I have a card inside a full height container and I want it centered both ways. I have seen margin auto, absolute with transforms, flexbox and grid. Which one should I use today?
Use grid or flexbox on the parent. Both are two lines and work for unknown sizes.
.parent {
display: grid;
place-items: center; /* align-items + justify-items */
min-height: 100dvh;
}
.parent {
display: flex;
align-items: center; /* cross axis (vertical) */
justify-content: center; /* main axis (horizontal) */
min-height: 100dvh;
}
In Tailwind: class="grid min-h-dvh place-items-center" or class="flex min-h-dvh items-center justify-center".
Other cases
margin-inline: auto (mx-auto) with max-width or width.text-align: center for inline content.align-items: center on the flex parent beats the old line-height hack.position: relative parent: position: absolute; inset: 0; margin: auto; plus a size, or top: 50%; left: 50%; translate: -50% -50%. This works but is the last resort; the translate approach can blur text on some displays.Why it fails
min-height or a height. height: 100% needs every ancestor to have a height, which is why min-height: 100dvh is easier.margin: auto in a block container and expected vertical centering. Auto vertical margins only work in flex or grid.justify-content and align-items swap meaning when flex-direction: column.Experiment with values in the flexbox playground.