How to center containers using HTML and CSS

Rayan Kazi
3 min readJul 8, 2021

--

This dreaded question has stumped and tormented many web developers for ages. There are many ways to do it, but here are the 3 most practical and easy ways to do it.

We will start with 2 files, index.html, and style.css, with the stylesheet being linked to the HTML file through a link tag. Inside the body there will be an article tag, and inside the article tag is a div with a class “centered”.

Boilerplate code that we will be using

Using Absolute Positioning

The first trick to center a div horizontally and vertically is absolute positioning. Select the centered class and make its position absolute. Using the CSS offsets, offset the top and left by 50%. Then move it back by transforming it using the translate function.

Use absolute positioning to center a DIV

This confusing hack was the standard until the new CSS Flexbox came around, which made it even easier to center a container.

Using Flexbox

To do this, we are going to add the class of “parent” to the article tag and remove the “centered” class from the child div.

Modified article and div tag

For adding the styling, first select the class parent, and make it a flex container. Then align the items to the center and justify the content to be in the center.

Use flexbox to center a div

Flexbox made centering containers very easy for developers, but you can use even fewer lines of code by using CSS Grid.

Using Grid

To put a container in the center, make the container a grid layout, and place the items in the center using the “place-items” property.

Using the Grid layout to center a DIV

As you can see, using the Grid layout is by far the easiest way to center a container, and it uses the least amount of code.

Summary

In all, all of these ways are great ways to center containers. Choosing one really comes down to context. If you already have a container with absolute positioning and need to place it in the center, using the absolute positioning technique. If you have a container apart of a grid layout that needs to be centered, use the grid layout technique, etc. Any one of these techniques should be more than enough to suit a developer’s needs.

Thanks for reading till the end 😊. Signing Off

Feel free to reach out to me through my GitHub or email me at rayan.quack.you@gmail.com

--

--

Rayan Kazi
Rayan Kazi

Written by Rayan Kazi

Hello, my name is Rayan. I am a passionate developer who loves to learn and solve problems!

No responses yet