How to Center an Absolutely Positioned Element in CSS?

To center an absolutely positioned element, you can use the top and left properties in combination with the transform property.

For example, if we want to center the element both horizontally and vertically, we have to first set the top and left properties to 50%. But, this will only center the top-left corner of the element to the center, not the whole element.

Therefore, we have to pull the element back by -50% using the translate(-50%, -50%) function. If you do this, the absolutely positioned element will be perfectly centered within its parent container.

Let’s say we have a div element with a class child in our HTML file:

<div class="parent">
    <div class="child">This div is absolutely positioned.</div>
</div>

The position of this child div is set to absolute. Now, we want to center it within its parent container whose position is set to relative so that the child div could be positioned relative to the parent container.

Here is the full CSS code with a live example:

Example:

.parent{
    position: relative;
    height: 200px;
    border: 2px solid red;
}
.child{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /* Pull back by -50% */
    background-color: yellow;
}

It will produce the following output:

Center an absolutely positioned element in CSS

Method 2 – Using margin: auto;

You can also center the absolutely positioned elements using margin: auto;. But margin: auto; doesn’t work directly on absolutely positioned elements.

You first have to set the left and right properties to 0 if you want to center the element horizontally using margin: auto; and if you also want to center the element vertically, you have to set the top and bottom properties to 0.

See the following example:

Example:

.parent{
    position: relative;
    height: 200px;
    border: 2px solid red;
}
.child{
    position: absolute;
    width: 50%;
    height: 30px;
    margin: auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: yellow;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.