And they offer a world of possibilities for positioning and alignment of content (not only centering.) But then, out came new ways of laying out content in CSS: Flexbox and Grid.
The previous method has worked for a long time, and it can still be handy. Combined with the transform, this may cause the element to overlap other things on the page. One con of this method is that by using position: absolute, we are getting the element out of the normal flow of the page. In addition, it doesn't depend on any other element (although you may need a position in the container) or on additional HTML elements. I like it because it is straightforward (just four CSS properties). This was a common way of centering elements horizontally and vertically for a while. So by translating -50%, we are translating half its size to the left and top, respectively. The percentage in the translation is relative to the element's size. The idea is to absolute-position the element to 50% top and left, and then translate it by half its size using a transform: This method is close to the previous one.
So we would end up with "magic numbers" in the code. But back then, CSS custom properties were not supported by that many browsers, and the support for calc was slightly better.Īnd yet, we still need to specify a width and height, which is not always possible. Some people may say, "you can use CSS variables and the calc function to avoid those issues," and they will be correct.
If you prefer to watch a video version of this article, visit my YouTube channel: This article will show five different ways of centering vertically and horizontally with HTML+CSS, presented in chronological order: from how it was done in the past (which we should avoid now) to the modern ways of centering content in the present.