1. Center horizontally and vertically with Flexbox
This is the modern default. Give the parent a height so there is room to center within.
.parent {
display: flex;
justify-content: center; /* left to right */
align-items: center; /* top to bottom */
min-height: 100vh;
}
2. Center only horizontally with margin auto
If you just need horizontal centering and the box has a width, the classic trick still works perfectly.
.box {
width: 300px;
margin: 0 auto;
}
3. The shortest version: CSS Grid
One declaration centers a child both ways. It is hard to beat for brevity.
.parent {
display: grid;
place-items: center;
min-height: 100vh;
}
Common mistakes
- The parent has no height. Vertical centering looks broken because there is nothing to center inside. Add
min-height. - Using
text-align: centeron a block. That only centers inline content like text, not a block-level div. - Forgetting the width with
margin: auto. Auto margins need a defined width to push against.
Frequently asked questions
Why is my div not centering vertically?
Almost always because the parent has no height. A flex or grid container only has vertical space to work with if it is tall enough, so set min-height on the parent.
Flexbox or Grid for centering?
Either is fine. Use Grid’s place-items: center when you want the shortest code; use Flexbox when the same container also lays out a row or column of items.
Want to understand the layout properties behind this? Work through our free HTML & CSS course.