How many ways can you center an element? Name the modern go-to.
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Modern default: display: grid; place-items: center on the parent (or flex + align-items/justify-content center). Legacy options include margin auto for horizontal blocks, absolute+transform, text-align/line-height tricks, and the new align-content: center shorthand.
Detailed explanation
Interviewers ask this to gauge fluency recency. The contemporary answer leads: grid's place-items: center centers any child both axes in two words — or flex equivalents (justify-content + align-items) when already using flex. Horizontal-only block centering remains margin-inline: auto with a constrained width. The old absolute + left/top 50% + translate(-50%, -50%) still appears for overlays where the element must ignore flow, though fixed-position modals increasingly use grid too. Text centering uses text-align (horizontal) and line-height equal to height (vertical, single-line). Worth naming: inset: 0 + margin auto for sized absolutely-positioned elements, and the brand-new top-level centering syntax (align-content: center making margin-auto-like behavior work everywhere in modern browsers) signals cutting-edge knowledge. Know tradeoffs: transform-based centering can blur text on fractional pixels; flex/grid keep text crisp.
Example
/* The 2024+ answer: */
.parent {
display: grid;
place-items: center; /* both axes, any child */
min-height: 100dvh;
}
/* Overlay variant: */
.overlay-child {
position: fixed;
inset: 0;
margin: auto;
width: fit-content; height: fit-content;
}Interview tip
Lead with place-items: center confidently, list two legacy methods briefly, close with dvh/align-content novelty. Brevity plus recency wins here.
Common mistakes
- Only knowing the absolute+transform approach.
- Using line-height hacks for multi-line vertical centering.