You don’t need jQuery to center

Posted by Andreas, filed under Tutorials.

In this brief tutorial I'll explain a few techniques for centering elements on the screen.

An old jQuery plug-in of mine redirects here.

If you know the width and height of the element, you can easily position its top left corner in the middle of the screen, and then pull the element up to the left half of its width/height using margin, like this:

Thanks to transform, we can center the element even without knowing its dimensions beforehand. Instead of margin we'll use translateX() and translateY():

And there you have it, completely JS-free centering.