How would you center a div inside a div?
Modern answer: `display: grid; place-items: center;` on the parent, or `display: flex; justify-content: center; align-items: center;`. Both center a child along both axes in one rule.
Centering is the canonical CSS interview question — interviewers want to see fluency across modern and legacy techniques.
Modern (use these):
- Flexbox
``css .parent { display: flex; justify-content: center; align-items: center; } ``
- Grid (shortest)
``css .parent { display: grid; place-items: center; } ``
- Grid with explicit cell
``css .parent { display: grid; } .child { margin: auto; } ``
Single-axis tricks:
margin: 0 auto;on a block-level child of known width — horizontal only.text-align: center;for inline/inline-block children — horizontal only.
Legacy (mention if relevant):
- Absolute positioning + transform:
``css .parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } `` Useful when the parent isn't flex/grid (e.g. centering inside a fixed background image).
Which to pick: default to grid place-items: center — shortest, most modern, browser-supported everywhere. Use flex if you also need to control wrapping or order.
Code
Follow-up questions
- •What's the difference between `align-items` and `align-content`?
- •How do you center the LAST flex item to the right while the rest are centered?
- •Why does `margin: auto` work for horizontal centering but not vertical (in normal flow)?
Common mistakes
- •Using `text-align: center` for non-text children and being surprised it doesn't center them.
- •Forgetting that `margin: 0 auto` needs an explicit width on the child.
- •Stacking `transform: translate(-50%, -50%)` plus a flex parent and double-centering.
Performance considerations
- •All these are zero-cost layout primitives. Avoid `transform` on huge subtrees only because it can promote to its own layer.
Edge cases
- •RTL languages — `justify-content: flex-start` is start-of-line, not 'left'. Prefer logical properties (`margin-inline`).
- •Centering a child that's bigger than the parent overflows; pair with `min-width: 0; min-height: 0;` to allow shrinking.
Real-world examples
- •Modal/overlay layouts almost always use flex/grid centering on the backdrop.