Center an element horizontally and vertically
The most reliable modern approach is flexbox on the parent container.
Code
<div class="center-box">
<div class="centered">I'm centered</div>
</div>
<style>
.center-box { display: flex; align-items: center; justify-content: center; height: 200px; background: #eee; }
.centered { padding: 1rem 1.5rem; background: #fff; border-radius: 8px; }
</style>
Preview
Explanation
align-items centers vertically, justify-content centers horizontally. The container needs an explicit height (or a flex context) — otherwise there's nothing to center within.
- With CSS Grid: display:grid; place-items:center; — an even shorter way to get the same result.
- With position:absolute + transform: translate(-50%,-50%) — an older approach, useful when flex isn't an option.