Home / Snippets / Layout /

Center with absolute + translate

Dead-center any element — even when you don't know its size.

Centered element
Widely Supported
layoutno-js

Quick implementation

.parent {
  position: relative;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Prompt this to your LLM

Includes role, constraints, and edge cases to handle.

You are a senior frontend engineer centering an overlay element.

Goal: Center an element of unknown size both horizontally and vertically inside a positioned parent using position: absolute and transform.

Technical constraints:
- Parent must have position: relative (or any non-static positioning).
- Child uses position: absolute with top: 50% and left: 50%.
- transform: translate(-50%, -50%) shifts the child back by half its own width and height.
- Do NOT set explicit width/height on the child — the technique must work with dynamic content.
- This approach removes the element from normal flow — use it for overlays, modals, and tooltips, not page layout.

Edge cases:
- The parent must have a defined height — otherwise top: 50% has nothing to reference.
- If the centered element is wider than the parent, it will overflow — add overflow: hidden or max-width.
- Sub-pixel rendering on translate can cause blurry text — use translate3d(0,0,0) to force GPU compositing if needed.

Why this matters in 2026

While place-items: center on grid is the modern go-to for centering, the absolute + translate technique remains essential for overlay patterns: modals, tooltips, image badges, and floating UI elements that sit on top of other content. It's the only centering method that works when the element needs to be removed from normal document flow.

The logic

top: 50% and left: 50% position the element's top-left corner at the parent's center. That overshoots — the element sits too far right and too far down. transform: translate(-50%, -50%) shifts it back by half its own dimensions. The result: the element's center aligns with the parent's center, regardless of how big the element is. Percentages in translate() reference the element's own size, not the parent's.

Accessibility & performance

transform is GPU-composited and doesn't trigger layout recalculations, so it's highly performant. For accessibility, absolutely positioned elements remain in the DOM and accessibility tree — screen readers can still read them. However, they're removed from normal flow, so ensure the tab order makes sense. For modals, pair this with focus trapping and aria-modal="true".