071-absolute-sizing

How to Center an Absolutely Positioned Element Using CSS

By | | JavaScript

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 CSS4 of great interest.

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:

  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;
  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 Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like Layout Building Techniques with HTML and CSS.

The Ultimate JavaScript Bundle: 2 books + 1 course

Buy now $39 Normally $117 - save 66%

Or get access to all SitePoint's Premium Content with a Learnable membership

Craig Buckler

Craig is a Director of OptimalWorks, a UK consultancy dedicated to building award-winning websites implementing standards, accessibility, SEO, and best-practice techniques.

More Posts - Website

{ 17 comments }

Ulyses May 23, 2010 at 4:24 am

First of all, I’m sorry Mr. Craig Buckler as I’m about to criticise, and that’s easy, the hard part is writing something people actually will read.

I’m not happy with the title: “How to Center an Absolutely Positioned Element Using CSS”. It need more specific info, clarity being one quality a beginner will appreciate. Confusion is the mother of all mistakes.

One logic question arises: if it’s absolutely positioned, why center? So I propose: “How to Horizontally Center an Absolutely Vertically Positioned Element Using CSS”. Or vice-versa, if it’s the case.

Then, also a beginner might appreciate an advice on if it’s a good practice or this is a wrong road for him. Often, you are headed against your own good, in a later sought as an unwanted developing direction. Quick fixes aren’t but a poke in the eye: bluring enough your vision to overlook it in the now, but later looks very ugly to the sane eye.

And I like to say thank you koyama for a beautiful suggestion. I like also your suggestion brothercake, nice to know.

And also thank you Mr. Craig Buckler for bringing this up, I learned some new things and ponder over them enough to make me think.

Hector Hurtado May 19, 2010 at 2:55 am

If you make it a habit to specify x y coordinates on absolutely positioned elements, then the most elegant method I have used so far is the one Koyama explains above.

And of course, stay away from absolutely positioned elements as much as you can :)

brothercake May 23, 2010 at 6:56 am

It’s a misnomer to say that absolute positioning should be avoided. It should be used with care, for sure, but contextual absolute positioning is a very useful trick, and doesn’t undermine layout flexibility, or font-sizing, or anything like that, the way absolute absolute positioning can.

Edson May 18, 2010 at 9:45 pm

Since I “discovered” that when a parent element has relative position (and this is everything!), 90% of my issues was solved…

vinhkhoa May 18, 2010 at 8:56 pm

Very clever. Thanks for the tip.

saramon May 18, 2010 at 7:38 pm

it’s that simple!

brothercake May 7, 2010 at 1:45 pm

@conradius – a possible solution to that would be a CSS media-query, that resets the margin when the viewport is narrower than the box, eg:
#inner
{
    width:500px;
    left:50%;
    margin-left:-250px;
}

@media all and (max-width:500px)
{
    #inner
    {
        margin-left:0;
    }
}

koyama May 6, 2010 at 12:16 am

It is perhaps worth mentioning that “margin: 0 auto” also works for absolutely positioned elements provided you specify explicit offset properties “left:0; right:0″.
The clean CSS way would probably be this (not working in IE6):
#outer
{
position: relative;
width: 40%;
height: 120px;
margin: 20px auto;
border: 2px solid #c00;
}
#inner
{
position: absolute;
width: 500px;
height: 100px;
top: 10px;
left: 0;
right: 0;
margin: 0 auto;
background-color: #00c;
}
Problem with “disappearing” box mentioned by conradius is also avoided this way.

Craig Buckler May 5, 2010 at 10:32 pm

Thanks Florent V.

SitePoint has visitors ranging from people writing their first HTML page to hard-core developers with many years experience. We feature new ideas and techniques but also common problems for novice developers.

This particular CSS issue doesn’t crop up very often, but it’s useful to know there’s a simple solution.

Florent V. May 5, 2010 at 9:57 pm

Old technique but it’s useful sometimes and it seems (from the comments) that many people didn’t know about it. Reminds me that when you have an audience, you can rehash the things you thought were absolutely obvious, and it will probably be useful to many readers. :)
Thanks to conradius for writing about the main drawback. It might be useful to add a mention of that in the main article. This problem is not obvious as designers are often unaware of what happens when an absolutely positioned element overflow the viewport. Quick reminder: if it overflow on the bottom or right of the viewport, you get scrollbars that allow you to see the overflowing content; if it overflows on the left or the top, the overflowing part is hidden (no scrollbars). (The left/right part may change for right-to-left languages, I never tested that.)

Manju May 5, 2010 at 8:14 pm

Its very easy!! n Useful!! Thank You!!!

conradius May 5, 2010 at 6:16 pm

There is one “big” drawback with this centring-technique: if the centred box is wider than the resized browser-window the centred box will begin to disappear on the left side. This is because of its negative left-margin that may push the box out of the viewport.
So keep in mind to just use this technique on boxes that are either small enough (like the given example above) or don’t have a crucial element on the left side (like a navigation).

centerme May 5, 2010 at 8:16 am

I usually do something like this

#centerme {
width:960px;
margin-left:-470px;
left:50%;
position:absolute;
}

ronald_poi May 5, 2010 at 2:29 am

So simple. Thank you!

Anonymous May 5, 2010 at 12:55 am

I thought everyone dropped support for Ie6 already, starting late 2009.

richthegeek May 4, 2010 at 11:57 pm

Useful to note, although far less likely to be used, that the same can be used for vertical centering.

pixel8me May 4, 2010 at 4:23 pm

A very simple yet effective solution to a problem I come across from time to time – but always forget! Thanks Craig

Comments on this entry are closed.