DEV3 Technologies home

DEV3 Developer Forum

What is the best way to center a div horizontally and vertically in CSS?

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?

#css#flexbox#grid#layout

0

1 reply

dev3 · Accepted answer

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

  • Horizontal only, block with a known width: margin-inline: auto (mx-auto) with max-width or width.
  • Text inside a box: text-align: center for inline content.
  • Single line vertical: align-items: center on the flex parent beats the old line-height hack.
  • Overlay inside a 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

  • The parent has no height. Centering is relative to the parent's box, so give it min-height or a height. height: 100% needs every ancestor to have a height, which is why min-height: 100dvh is easier.
  • You centered the child with 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.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.