CSS Centering Using CSS transform

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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 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%);
}

View example in JSFiddle

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, or fixed). Explore more in this fiddle and this documentation topic.
  • For horizontal-only centering, use left: 50% and transform: translateX(-50%). The same goes for vertical-only centering: center with top: 50% and transform: 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%; and margin-bottom: -50%;. View this fiddle for more information.


Got any CSS Question?