Using CSS transform

suggest change

CSS transforms are based on the size of the elements so if you don’t know how tall or wide your element is, you can position it absolutely 50% from the top and left of a relative container and translate it by 50% left and upwards to center it vertically and horizontally.

Keep in mind that with this technique, the element could end up rendered at a non-integer pixel boundary, making it look blurry. See this answer in SO for a workaround.

HTML

<div class="container">
  <div class="element"></div>
</div>

CSS

.container {
  position: relative;
}
.element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

View example in JSFiddle

Modern browsers support transform without prefixes. For ordinary centering, Grid or Flexbox is usually simpler because it does not require absolute positioning. The transform technique remains useful for overlays and other positioned elements.

MORE INFORMATION

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents