Codeflaps

Center an absolute positioned element in CSS

CSS positioning is one of the confusing thing in CSS. It needs to be rendered well, otherwise you may get confused. In CSS we can use the Absolute position to an element, only if its parent element has already been given a Relative position. We use the top, bottom, left and right attribute to position absolutely an element. But problem arises when we want to align center an absolute position element with respect to the parent element, which has already been positioned relatively.

In this tutorial I shall discuss this problem of alignment thoroughly, so that at the end of this tutorial you can able to align an absolute positioned element effortlessly.

The HTML markup 

The following HTML markup is used in this tutorial
<body>
  <div id="parent">
      <div id="child">
      </div>
  </div>
</body>

In this example I shall apply the relative position to the parent ID and absolute position to the child ID, and later we shall try to align center the absolutely positioned div that is the div with the child ID with respect to the parent ID.

The necessary CSS

The following CSS is required to align absolutely center the div with the ID child
#parent {
  width: 500px;
  height: 300px;
  position: relative; /*----RELATIVE----*/
  background: #FE2E2E;
  margin: 20px auto;
  }

#child {
  width: 350px;
  height: 150px;
  position: absolute; /*----ABSOLUTE----*/
  top:50%; /*----top----*/
  left:50%; /*----left----*/
  margin-left: -175px; /*----margin-left half of the width----*/
  margin-top: -75px; /*----margin-top half of the height----*/
  background: #5882FA;
  }

In the above CSS we have positioned the parent ID relatively and child ID absolutely. Our goal is to positioned the div with the child ID absolutely center the div with the parent ID. It can be done easily by adjusting the top and left position and top and left margin . As you can see we have applied the top position to 50% of the parent div, this will bring the upper edge of the child div to the center, keeping this in mind we then applied a top-margin equal to negative of half the height of child div. This steps will position the child div vertically center. Now to adjust the horizontal position, use the same trick, but this time you have to use the left position and margin-left attribute equal to negative of half the width of child div.

Full code snippet with the result

See the Pen kJquA by Jayanta Boruah (@Jayanta588) on CodePen.