Centering an Absolutely Positioned Element Using CSS

Centering an absolutely positioned element is a CSS challenge that I have always struggled with. I always find myself googling for the solution every now and then.

Today I came across this great article for exactly this problem and decided to share it with everybody and document it on my blog for easy referencing later!

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;
	top: 10px;
	left: 30px;
	right: 30px;
	background-color: #00c;
}

So, how can we center our box if it has fixed dimensions? The answer requires a little lateral thinking:

  1. First, we use left: 50%. Unlike background image positions, this will move the left-hand edge of the blue box to the center.
  2. 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-left to -50px to 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;
	height: 100px;
        width: 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!

Via: SitePoint

Advertisements