DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to center elements using the box model
Dany Paredes
Dany Paredes

Posted on • Updated on

How to center elements using the box model

A common task for web development is center elements, we can center the elements horizontal and vertically.

Center horizontal

Center horizontally is so easy, our element needs to have a width size, if not our element will take all space possible.
Set to 0 auto the margin, the element will take the same amount of space between left and right.

margin: 0 auto;
Enter fullscreen mode Exit fullscreen mode

Center Vertical

When we want center vertical, using box-model, we need an extra element as a container for the element and with full width, the element inside should have height, set the container with position absolute and take away 50% from top and using negative margin with the half value of the element.

{
  position: absolute;
  top: 50%;
  margin-top: half- height;
}
Enter fullscreen mode Exit fullscreen mode

Example

See the Pen center element with box model by Dany Paredes (@danywalls) on CodePen.

Photo by Thought Catalog on Unsplash

Top comments (0)

Make Your Github Profile Stand Out

Github is great, but have you considered how to make yours more attractive for potential employers or other visitors? Even non-tech ones like recruiters!

Take a couple of hours and show your best side as a person - and a programmer.