How to center an item

In this guide you can find out how to center an item inside another element, both horizontally and vertically.

Center a box

To center one box inside another using CSS you will need to use CSS box alignment properties on the parent container. As these alignment properties do not yet have browser support for block and inline layout you will need to make the parent a flex or grid container to turn on the ability to use alignment.

In the example below we have given the parent container display: flex; then set justify-content to center to align it horizontally, and align-items to center to align it vertically.

html
<div class="wrapper">
  <div class="box">center me!</div>
</div>
css
.wrapper {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.box {
  background-color: rgb(69 164 181);
  border-radius: 5px;
  padding: 10px;
  color: #fff;
}

Note: You can use this technique to do any kind of alignment of one or more elements inside another. In the example above you can try changing the values to any valid values for justify-content and align-items.

See also