CSS Center A Div Horizontally & Vertically

HTML & CSS

There are a couple of ways you can center an HTML element vertically and horizontally to its parent container.

Display Table

Define a parent div with the class name .box.

The child div has classname .inner-box and it has image element inside.

<div class="box">
  <div class="inner-box">
    <img src="https://picsum.photos/200/200"/>
  </div>
</div>

In CSS, add display:table property to the parent div which is .box

This will affect the full width so add width:100% to it as well.

Inside .inner-box, center the image tag horizontally using text-align:center property as it’s the inline element.

Finally, add vertical-align:middle to the inner div which is pushed to vertically center to its parent element.

html, body {
  margin:0px;
  height: 100%;
}
.box {
  width: 100%;
  height: 100%;
  display: table;
}
.inner-box{
  text-align:center;
  display:table-cell;
  vertical-align: middle;
}

Padding

Using padding, we can easily make the inner div vertically centered.

If you use this approch, do not add height property to the outer-box.

html,body {
  margin:0px;
}

.outer-box {
  width: 100%;
  padding:60px 0;
  text-align: center;
  background: orange;
  color: white;
}

.inner-box {
  width:100px;
  background:purple;
  margin:0 auto;
  font-size:2em;

}

Display: Flex

Setting display flex to the outer container is the easiest way to arrange its child to center in both directions.

<div class="box">
  <img src="https://picsum.photos/200/200" />
</div>
html, body {
  height:100%;
  margin:0;
}

.box {
  height:100%;
  background:purple;

  display:flex;
  justify-content:center;
  align-items:center;
}
namevaluedescription
height100%The 100% value will stretch the .box element to match its viewport height of 100%.

Make sure to add height:100% to HTML & body selectors.
displayflexThis makes the .box element to be flexbox which means we can easily arrange its children.
flex-directionrowBy default, flex-direction is set to row which means all the children elements are laid out next to each other.
justify-contentcenterThis will center the child elements vertically and stretch it to match the height of the parent element.
align-itemscenterThis will center the .img element horizontally to its parent container.