Centering Absolutely Positioned Elements
The classic technique for centering: set top/left to 50% and use transform to offset by half the element's size.
The classic technique for centering: set top/left to 50% and use transform to offset by half the element's size.
/* Center horizontally and vertically */
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Center horizontally only */
.centered-x {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
/* Center using inset + margin: auto */
.centered-modern {
position: absolute;
inset: 0;
margin: auto;
width: fit-content;
height: fit-content;
}
The inset: 0 + margin: auto technique works without knowing the element's dimensions and is semantically clear.