Centering an HTML Element in 2025
TLDR: Use CSS Grid Layout
This is the modern way to both vertically and horizontally center an HTML element, using the least amount of code, and is supported in all major browsers:
.center-children-grid {
display: grid;
place-items: center;
}
Flexbox
If you're like me this is still what you reach for, mainly because it became widely supported before the Grid method. It's only one line longer, and enjoys more support in older browsers.
.center-children-flex {
display: flex;
justify-content: center;
align-items: center;
}
Conceptually, Flexbox is designed to handle layout along a single axis, either horizontal or vertical. In contrast, CSS Grid is designed for multi-dimensional layouts.
Legacy Knowledge
The pre-flex way of centering an element involves setting a parent element to position: relative
, and then absolutely positioning a child element inside it. The size of the child must be
known up front so that you can appropriately size the parent.
.legacy-center-parent {
position: relative;
}
.legacy-center-child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
This approach is suboptimal due to the verbosity, but more importantly because the parent's size does not adjust to that of the child. However, this technique is great for when you want to create a 'stack' of elements that are all centered and occupying the same area of space, layered one on top of the other.
Bonus: Margins
This approach only centers an element horizontally, unlike the first three techniques, limiting its usefulness. Also, note that this applies to the child you want to center, rather than the parent.
.center-self-horizontally {
margin: 0 auto;
}
This is one of the oldest CSS tricks, and is useful when you want to center an element horizontally without styling a parent container.