HTML & CSS - - By Craig Buckler

How to Center an Absolutely Positioned Element Using CSS

This article was written in 2010 and remains one of our most popular posts. If you’re keen to learn more about CSS techniques, you may find this recent article on Selectors Level 4 in CSS of great interest.

Centering an absolutely positioned element is a CSS challenge that occurs now and then. The solution seems 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 value 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 not concerned 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;
}
 

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 the box’s width. In our example, we must set margin-left to -50px to shift the box back to the right place.

Here is the code:

.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.

If you enjoyed reading this post, you’ll love SitePoint Premium; the place to learn fresh skills and techniques from experienced developers. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like CSS Master.

Comments on this article are closed. Have a question about CSS? Why not ask it on our forums?

Sponsors