Using CSS transform
suggest changeCSS 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%);
}
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
- The element is positioned against the nearest ancestor whose
positionis notstatic(relative,absolute,fixed, orsticky), or the initial containing block. Explore more in this fiddle and this documentation topic. - For horizontal-only centering, use
left: 50%andtransform: translateX(-50%). The same goes for vertical-only centering: center withtop: 50%andtransform: translateY(-50%). - Using this method on an element whose width or height is not a fixed length can make the centered element appear squished. This mostly happens with elements containing text, and can be fixed by adding:
margin-right: -50%;andmargin-bottom: -50%;. View this fiddle for more information.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents