Fix margin auto not working with position absolute Problem in CSS

The margin: auto; is a very popular fix in CSS to center an element horizontally. But, if the element’s position is set to absolute and you directly apply margin: auto; on it, it’s not going to work.

So, if you want to center an absolutely positioned element with margin: auto;, you also have to set the left and right properties to 0 along with a fixed width of the element such as 100px, 40%, and so on.

Let’s say we have a div element whose position is set to absolute. This div is inside another div element(parent div) whose position is set to relative so that the inner div could be positioned relative to it.

<div class='parent'>
    <div class='child'>This is the centered child div.</div>
</div>

We want to center the inner div horizontally inside the outer div. To achieve this, we have to first give a fixed width to it such as 40%, 100px or so, and then we have to explicitly set the left and right properties to 0.

This will automatically pull the inner div to the center of its container div element:

Here is the CSS code for it:

.parent{
    position: relative;
    border: 2px solid red;
    height: 70px;
    padding: 10px;
}
.child{
   position: absolute;
   width: 40%;
   margin: auto;
   left: 0;
   right: 0;
   background-color: springgreen;
}

This is how the inner div will look like after applying the above styles:

Fix margin auto not working with position absolute Problem in CSS

If you also want to center the absolutely positioned element vertically, you have to first give it a fixed height and then set the top and bottom properties to 0.

This will automatically center the element vertically inside its container:

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

The above CSS code will produce the following result:

Center absolutely positioned element with margin auto

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.