Absolutely Position Element Center

Center An Absolutely Positioned Element

The method above works to automatically center one item inside another, but the method assumes that you’re using the default positioning context: static. If you have absolute positioning applied, this method goes out the window.

With Fluid Width

The method above only works if the parent container has a static width. Given the popularity of responsive design though, more and more containers are going the fluid route lately. This means that we’ll need another way to center the child that isn’t dependent on the width of the parent.

To accomplish this, we need to use a percentage for the left value. The obvious answer is to use 50%, but that won’t really work because you’re not accounting for the width of the element that you’re centering. To make it work, we need to add in a negative left margin of half the width of the child element.

Imgur

.container {
  height: 300px;
  width: 70%;
  background: #eee;
  margin: 10px auto;
  position: relative;
}

.box {
  height: 100px;
  width: 100px;
  background: #222;
  position: absolute;

  /*Centering Method 2*/
  margin: 0px 0 0 -50px;
  left: 50%;
}

It’s important to note that this would also work if our child element had a fluid width. We use the same steps as before and come up with something like the following:

.container {
  height: 300px;
  width: 70%;
  background: #eee;
  margin: 10px auto;
  position: relative;
}

.box {
  height: 100px;
  width: 70%;
  background: #222;
  position: absolute;

  /*Centering Method 2*/
  margin: 0px 0 0 -35%; /* Half of 70% /*
  left: 50%;
}

Dead Center an Element

it’s time to tackle the puzzle of perfectly centering an element both horizontally and vertically.

Fortunately, to pull this off, we can use the same method that we just learned, we just have to account for height. This time around we’re also going to center both the parent and the child both vertically and horizontally.

.container {
  height: 300px;
  width: 300px;
  background: #eee;
  position: absolute;

  margin: -150px 0 0 -150px;
  left: 50%;
  top: 50%;
}

.box {
  height: 100px;
  width: 100px;
  background: #222;
  position: absolute;

  /*Centering Method 2*/
  margin: -50px 0 0 -50px;
  left: 50%;
  top: 50%;
}