DEV Community

Ayoazeez26
Ayoazeez26

Posted on

Centering content in the middle of a page

Have you ever needed to center an element to the middle of a page? I would proceed to explain the simple way you can achieve that :)

Challenge Image

The image above was gotten from a chellenge on Frontend Mentors where you sign up and take challenges and try to make your solution look as close to the design as possible.

As you can see from the image above, the container of the whole content is centered in the page. This is what my solution currently looks like

Unfinished Solution

As you can see, it's perfect with the exception of the container being in the center of the page. We will proceed to make it centered now.

Absolute position styling to parent class

Setting the position of the container to absolute takes it out of the flow of the document. Next thing to do is to set the top and left properties to 50% each.

set top and left properties to 50%

The reason we did that was to set the container to 50% from the top of the page and 50% from the left. Our container now looks like this

challenge after adding 50% to left and top

what actually happens here is that the origin of the container is its top left position, looking objectively at our solution would show you that the top left corner of our container is actually at the center of the page.

To make our container body appear at the body instead of just the top-left corner, we add a final style property.

Final code

What the transform translate property does is to move the container and in general, it acts relative to the body of the container so the (-50%,-50%) moves the container backwards half of it's width and height, so originally if we had our width set to 600px, -50% moves it backward 300px and same goes for the height.

Our container should now look like this

Final challenge look

So, with just 4 style properties, we were able to style our container and center it on our page. I hope you have a better understanding of how centering an element works now.

Here's a link to the github repo

Top comments (0)