Centering an absolutely positioned element is a CSS challenge that occurs now and then. The solutions seem obvious once I’ve done it, but I still find myself googling the problem every few months.
Horizontally centering a static element in CSS is normally handled by setting the left and right margins to auto, for example:
#myelement
{
margin: 0 auto;
}
However, this won’t work on an absolutely positioned element. Its location is determined in relation to the most immediate parent element that has a position of absolute, relative, or fixed.
In the following example, the relative red square has a width set to 40% of the available space. The top-left of the absolutely positioned blue square is positioned 30px across and 10px down:
#outer
{
position: relative;
width: 40%;
height: 120px;
margin: 20px auto;
border: 2px solid #c00;
}
#inner
{
position: absolute;
width: 100px;
height: 100px;
top: 10px;
left: 30px;
background-color: #00c;
}
If we’re unconcerned about the exact dimensions of our blue box, we could omit the width setting and set the same left and right values. This would effectively center our blue box:
#outer
{
position: relative;
width: 40%;
height: 120px;
margin: 20px auto;
border: 2px solid #c00;
}
#inner
{
position: absolute;
height: 100px;
left: 30px;
top: 10px;
right: 30px;
background-color: #00c;
}
(Note: this does not work in IE6 … does that surprise you?)
So, how can we center our box if it has fixed dimensions? The answer requires a little lateral thinking:
- First, we use
left: 50%. Unlike background image positions, this will move the left-hand edge of the blue box to the center. - Since our box is too far to the right, we use a negative left margin that’s half its width. In our example, we must set
margin-leftto-50pxto shift the box back to the right place:
#outer
{
position: relative;
width: 40%;
height: 120px;
margin: 20px auto;
border: 2px solid #c00;
}
#inner
{
position: absolute;
width: 100px;
height: 100px;
top: 10px;
left: 50%;
margin-left: -50px;
background-color: #00c;
}
The blue box will remain centered no matter how the width of the outer element changes.




