How to Center an Absolutely Positioned Element in a Div

In CSS, centering an absolutely positioned element can cause some difficulties. It can be especially complicated if the width of the element is unknown.

Below, we’ll discuss two cases when we know the width, and the width is unknown.

First, we will center an absolutely positioned element, the dimensions of which are unknown.

Create HTML

  • Create two <div> elements and add content to the inner box.
  • Use a <br> tag to add a line break.
<body>
  <div class="outer">
    <div class="inner">
      A centered text.
      <br/>The length of the text, height or width does not matter.
    </div>
  </div>
</body>

Add CSS

Set the position to "relative" for the "outer" class and "absolute" for the "inner" one.

.outer {
  position: relative;
  margin: 5%;
  width: 80%;
  height: 500px;
  border: 2px solid #1703fc;
}

.inner {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  max-width: 50%;
  text-align: center;
  border: 2px solid #468a4d;
}

Here is the full code.

Example of centering an absolutely positioned element with unknown dimensions:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .outer {
        position: relative;
        margin: 5%;
        width: 80%;
        height: 500px;
        border: 2px solid #1703fc;
      }
      .inner {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        max-width: 50%;
        text-align: center;
        border: 2px solid #468a4d;
      }
    </style>
  </head>
  <body>
    <div class="outer">
      <div class="inner">A centered text.
        <br/>The length of the text, height or width does not matter.</div>
    </div>
  </body>
</html>

Result

A centered text.
The length of the text, height or width does not matter.

In the example above, the left property is relative to the parent element, while the transform is relative to its parent’s width/height. Thus, you can have a centered element with a flexible width on both the child and parent elements.

Next, we’ll show an example of centering an absolutely positioned element, which has exact dimensions. Here, the inner box will remain centered regardless of the width of the outer element.

Example of centering an absolutely positioned element with fixed dimensions:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .outer {
        position: relative;
        width: 40%;
        height: 120px;
        margin: 20px auto;
        border: 2px solid #468a4d;
      }
      .inner {
        position: absolute;
        width: 100px;
        height: 100px;
        top: 10px;
        left: 50%;
        margin-left: -50px;
        background-color: #1703fc;
      }
    </style>
  </head>
  <body>
    <div class="outer">
      <div class="inner"></div>
    </div>
  </body>
</html>

Do you find this helpful?

Related articles