---
title: "How to center elements using the box model"
date: "2020-08-24"
slug: "how-to-center-elements-using-the-box-model"
author: "Dany Paredes"
canonical: "https://danywalls.com/how-to-center-elements-using-the-box-model"
description: "A common task for web development is center elements. We can center the elements horizontally and vertically. Center horizontal Center horizontally is so accessible. Our element needs to have a width size. If not, our element will take all space poss..."
---

A common task for web development is center elements. We can center the elements horizontally and vertically.

## Center horizontal
Center horizontally is so accessible. Our element needs to have a width size. If not, our element will take all space possible.
Set the margin to 0 auto. The element will take the same amount of space between left and right.
```javascript
margin: 0 auto;
```
## Center Vertical 
When we want center vertical, using box-model, we need an extra element as a container. With full width, the aspect 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.
```javascript
{
  position: absolute;
  top: 50%;
  margin-top: half- height;
}
```

## Example
[See CodePen Example](https://codepen.io/danywalls/pen/wvBQaxK)

Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Thought Catalog</a> on <a href="https://unsplash.com/s/photos/center?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
  

