If you’re doing website development with HTML and CSS, one of the minor issues that you may have encountered at some point in your web design career is to centre contents horizontally and vertically. There are lots of ways to do it. You might define a containers width and height, and then position its content at the middle – but you might have issues when it comes to responsiveness and a fluid layout. So, here are three (3) ways you can centre contents horizontally and vertically nowadays (there might be new and better techniques introduced in the future).
1) Using position: absolute and transform.
For quite some time these past few years (before the next two techniques here are introduced), this has probably been the most popular way to centre contents horizontally and vertically.
Using this method, you set the position for the content as absolute, move them 50% horizontally and vertically, and then use transform to fully centre the content on the x and y axis. Using this method, this would be the HTML and CSS codes:
<div class=“container”> <div class=“content”>This is a content</div> </div>
This would centre the content horizontally and vertically, relative to the container. However, according to this article by Alvaro Montoro, one negative aspect of this method is that it gets the element out of the normal flow of the page because of the usage of position: absolute styling.
2) Using Flexbox
As mentioned above, the absolute positioning & transform method was the most popular and effective method to centre contents horizontally and vertically; until out comes Flexbox and Grid. With Flexbox and Grid, the styling to centre contents is applied to the container itself, so the process is much more natural. Using the same HTML example above, the CSS code to centre contents using Flexbox would be like this:
That is all the code needed. There is no need to apply styling to the element because using Flex, the styling is applied to the container. There are lots of other cool ways to arrange and align content using Flexbox – more than what the previous method can offer. If you haven’t used Flexbox before: learn it and use it!
3) Using Grid
Grid is more or less like Flexbox. It acts more or less like a single cell table, but with proper semantics and without the burden of additional elements. And it is much more simple than Flexbox:
And that’s it! You will have your content positioned perfectly in the centre.