Skip to content

All the Ways to Center a Div

October 1, 2022 | 08:12 PM

Centering a div is something we need to do all the time as web developers, and yet it still can be a challenge. There are many approaches you can take to accomplish it. Below I’ll explore all the ways to center one div inside another.

All of the examples will be using the following HTML:

<div class="outer-div">
  <div class="inner-div"></div>
</div>

Each example has these shared base styles:

.outer-div {
  background-color: red;
  width: 150px;
  height: 150px;
}

.inner-div {
  background-color: blue;
  width: 50px;
  height: 50px;
}

There is a 150x150 red outer div, and a 50x50 blue inner div. The goal is to find all the ways to center the blue div vertically and horizontally inside the red div and get this end result:


Table of Contents

Open Table of Contents

1. Flexbox

.outer-div {
  display: flex;
  justify-content: center;
  align-items: center;
}

OR

.outer-div {
  display: flex;
  justify-content: center;
}

.inner-div {
    align-self: center;
}

OR

.outer-div {
  display: flex;
}

.inner-div {
    margin: auto;
}

2. CSS Grid

.outer-div {
  display: grid;
  place-content: center;
}

OR

.outer-div {
  display: grid;
  align-items: center;
  justify-content: center;
}

OR

.outer-div {
  display: grid;
}

.inner-div {
  align-self: center;
  justify-self: center;
}

3. Absolute Positioning

.outer-div {
  position: relative;
}

.inner-div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

OR

.outer-div {
  position: relative;
}

.inner-div {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

Try these out yourself in CodePen!

See the Pen Center a Div by Jcanotorr06 (@jcanotorr06) on CodePen.