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 being 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%);
}
CROSS BROWSER COMPATIBILITY
The transform property needs prefixes to be supported by older browsers. Prefixes are needed for Chrome<=35, Safari<=8, Opera<=22, Android Browser<=4.4.4, and IE9. CSS transforms are not supported by IE8 and older versions.
Here is a common transform declaration for the previous example:
-webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera, Android */
-ms-transform: translate(-50%, -50%); /* IE 9 */
transform: translate(-50%, -50%);
For more information see canIuse.
MORE INFORMATION
- The element is being positioned according to the first non-static parent (
position: relative
,absolute
, orfixed
). 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 a non-static width/height elements with this method of centering can cause the centered element to 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.