Centering content in the middle of a page
Ayoazeez26
Posted on March 30, 2021
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 :)
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
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.
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.
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
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.
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
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
Posted on March 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.