SyntaxStudy
Sign Up
CSS Centering with Absolute Positioning
CSS Intermediate 5 min read

Centering with Absolute Positioning

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.

Example
/* 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;
}
Pro Tip

The inset: 0 + margin: auto technique works without knowing the element's dimensions and is semantically clear.