How to center a div horizontally and vertically in CSS
· Category: HTML & CSS
Short answer
The modern, recommended way is Flexbox or CSS Grid. Both allow centering with just a couple of properties on the parent container.
Steps
- Flexbox: Set
display: flex,justify-content: center, andalign-items: centeron the parent. - Grid: Set
display: gridandplace-items: centeron the parent. - Absolute positioning: Set
position: absolute,top: 50%,left: 50%, andtransform: translate(-50%, -50%)on the child.
Example
/* Flexbox */
.parent {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Grid */
.parent-grid {
display: grid;
place-items: center;
min-height: 100vh;
}
/* Absolute positioning */
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Tips
- Prefer Flexbox and Grid over absolute positioning because they adapt dynamically to content size.
- For single-axis centering, use
justify-content(main axis) oralign-items(cross axis).