Flexbox — The Recommended Method
Flexbox is the cleanest way to center both horizontally and vertically. Apply it to the parent element:
/* Center a child both ways */
.parent {
display: flex;
align-items: center; /* vertical */
justify-content: center; /* horizontal */
}
/* Minimum height so there's space to center in */
.parent {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh; /* full viewport */
}
✅ Best for: Cards, modals, hero sections, buttons, nav items — anything where you control the parent element.
CSS Grid
Grid has an even shorter syntax for centering using place-items:
.parent {
display: grid;
place-items: center; /* centers both axes in one line */
min-height: 100vh;
}
place-items is shorthand for align-items + justify-items. This is the most concise centering solution in CSS.
Absolute Positioning
For elements positioned outside the normal flow (overlays, tooltips, loading spinners):
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
💡 Why transform?
top: 50% and left: 50% position the element's top-left corner at center. The translate(-50%, -50%) then shifts it back by half its own width and height — perfectly centering it.Centering Text
/* Horizontal only */
p { text-align: center; }
/* Vertically in a fixed-height element */
.btn {
height: 44px;
display: flex;
align-items: center;
padding: 0 20px;
}
/* Single-line text vertical centering (old method) */
.btn {
height: 44px;
line-height: 44px; /* match height */
}
Centering Images
/* Block-level centering */
img {
display: block;
margin: 0 auto;
}
/* Inside a flex container */
.card {
display: flex;
flex-direction: column;
align-items: center; /* centers img horizontally */
}
/* Object-fit for cropped images */
.avatar {
width: 80px;
height: 80px;
object-fit: cover;
object-position: center;
}
Which Method to Use?
| Situation | Best Method |
|---|---|
| Center inside a container | Flexbox align-items + justify-content |
| Center on the whole page | Grid place-items: center on body |
| Overlay / modal / tooltip | Absolute + transform: translate(-50%,-50%) |
| Centering text | text-align: center |
| Centering a block element | margin: 0 auto with a set width |