How can I center a fixed-width element horizontally in its parent?
Quick answer
Give the block a constrained width and set its left and right margins to auto. When the parent has extra horizontal space, the automatic margins share it evenly and center the block. If the parent is as wide as or narrower than the block, there is no positive leftover space to share, so the block may overflow instead of fitting. [S1]
The question, the details, the next step.
A practical checklist
Give the block a constrained width.
Set both horizontal margins to
auto.Check whether the parent is wider than the block.
Decide how the layout should handle a parent narrower than the chosen width.
A few more useful answers
Will automatic margins make an oversized child fit?
No. They share available horizontal space; if the child is as wide as or wider than its parent, there is no positive leftover space to distribute. The child may overflow. [S1]
What width should I use if the parent can be narrow?
Choose a width that fits the parent for the layout you need. Automatic margins can center the block when there is horizontal space, but do not reduce its width. [S1]
Sources
References used for this guide.
- [S1] Box alignment for block layouts: Centering with auto margins developer.mozilla.org · Checked
