3 Ways To Center Horizontally And Vertically With CSS In 2022
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 center 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 center 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 center 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 center the content on the x and y axis. Using this method, this would be the HTML and CSS codes:
HTML
<div class="container"> <div class="content">This is a content</div> </div>
CSS
.container { position: relative; } .content { position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
This would center 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 center contents horizontally and vertically; until out comes Flexbox and Grid. With Flexbox and Grid, the styling to center contents is applied to the container itself, so the process is much more natural. Using the same HTML example above, the CSS code to center contents using Flexbox would be like this:
CSS
.container { display: flex; align-items: center; justify-content: center; }
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:
CSS
.container { display: grid; place-items: center; }
And that's it! You will have your content positioned perfectly in the center.