Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

Position Absolute Horizontal and Vertical Center via CSS

Recently, a reader named Max encountered some scrolling issues while implementing our absolutely centered layout technique. Of course, by “absolutely centered” we are referring to content that remains positioned dead-center regardless of how the browser is resized. After noticing the scrollbar deficiency, Max kindly dropped a comment to explain the issue:

the div solution works well, only one problem maybe somebody can help: if you make the browser window smaller then the div is -> the scrollbar doenst fit right und you cant scroll over the whole area.

Apparently, because the horizontal/vertical centering method outlined in our original article employs absolute positioning with negative margins, resizing the browser to be smaller than the centered division results in cropped content that is inaccessible via scrollbar. Although this is the first I have heard about this issue, I went ahead and examined the alternate centering technique via the link generously shared by Max.

As it turns out, the proposed solution to the broken-scrollbar problem takes an entirely different approach to the absolute centering of a division (div). Rather than using an absolutely centered wrapper div to align the content, this alternate approach employs a floated “distance” div to set the relative height, and then floats the “content” div relative to the distance div. Sound confusing? Let’s check out the core functionality behind the technique..

Step 1:

First, throw down this (X)HTML markup:

<body>

   <div id="distance"></div>
   <div id="content">
      <!-- absolutely centered content -->
   </div>

</body>

Step 2:

Next, apply the following (heavily commented) CSS:

html, body {
	height: 100%;         /* required */
}
body {
	text-align: center;   /* horizontal centering hack for IE */
	padding: 0;           /* required to "hide" distance div */
	margin: 0;            /* required to "hide" distance div */
}
div#distance { 
	margin-bottom: -10em; /* half of content height */
	background: red;      /* temporary - used to see div */
	width: 1px;           /* required to "hide" distance div */
	height: 50%;          /* required */
	float: left;          /* required */

}
div#content {
	position: relative;   /* positions content on top of distance */
	text-align: left;     /* horizontal centering hack for IE */
	height: 20em;         /* required - desired height */
	width: 40em;          /* required - desired width */
	background: blue;     /* cosmetic */
	margin: 0 auto;       /* required */
	clear: left;          /* required */
}

Step 3: (optional)

Finally, if you are concerned about supporting the now-archaic Internet Explorer for Mac, use the following hack:

<style type="text/css">@import("ie5mac-only.css");</style>

..to import a stylesheet with this rule (required only by IE5 for Mac):

html, body {
	height: auto;   /* required only for IE5 mac */
}

Discussion

Examining our CSS-centering code, we first notice the straightforward (X)HTML markup. As with our original method, only two divisions are required to make it work. Looking at the heavily commented CSS code, the trick behind this technique becomes clear.

After setting the document height to 100%, we invoke the ancient powers of the IE centering hack to center the “content” division horizontally. No surprises there. Then, the ol’ vertical magic happens thanks to the “distance” div, which is set at 50% height and floated left with a width of 1px. Finally, positioned relative to the distance div, the content div copmpletes the IE centering hack and establishes the final width and height of the absolutely centered division.

If I did my job, everything you need to implement this technique is explained via the comments in the code. Note that the last two blocks of code apply only to IE5 Mac, so feel free to exclude it if you could care less about such antiquity1. And finally, to get a better idea of how it works, try removing the padding and margin from the body selector and check the results.

Conclusion

Overall, this seems like a solid absolute-centering technique that would be somewhat easier to implement (less math) than our original version. Especially if you are experiencing the same scrollbar issues as Max, I would definitely give this method a try. According to the original author, this technique works in just about every browser that you would ever need. Of course, if you are concerned about potential layout conflicts arising due to floating your primary layout divs, you may want to consider the absolute-positioning technique. In any case, having a choice when it comes to CSS layouts is definitely a good thing ;)

Footnotes

  • 1 Omitting the associated conditionally commented CSS rules for IE5mac will result in content that is repositioned outside of the browser window. However terrible, this only seems to happen when using an (X)HTML doctype. If your doctype happens to be HTML Transitional, this problem should not occur.

About the Author
Jeff Starr = Web Developer. Book Author. Secretly Important.
The Tao of WordPress: Master the art of WordPress.

29 responses to “Position Absolute Horizontal and Vertical Center via CSS”

  1. Christian 2007/12/10 9:58 am

    Thanks for the code Perishable.
    It gives me inspiration for my current project. However, I still face some problems in combining codes from various source.
    My goal is similar to the current Hotmail login page where:
    *) the vertical distance of centered stuff to the browser’s border will shrink if I shrink the browser vertically and
    *) the footer always stick to the bottom.
    Do you have any suggestion?
    or anyone?

    Thanks in advance =)

  2. I had many problems with using CSS positioning. Your article helped to clarify it.
    Thank you

  3. Perishable 2008/01/27 8:13 am

    You are welcome, Nishanthe — thank you for the positive feedback! :)

  4. Thanks very much for your code and clarification on everything. I was having a wicket time on my /specs page with trying to get my images centered correctly. It would work in one browser and would be terrible in the next. In addition, I WAS using tables to try and break it apart and it still didn’t help.

    It still isn’t PERFECT in IE but its very close and now works perfectly in firefox.

    I really wanted to say thanks, you saved me a ton of headaches! Great job.

  5. NicMartel 2008/02/07 3:11 pm

    [Display: none;]problem!

    2 DIVs, both float: right; DIV1 display: block; has a background picture and some wording. DIV2 display: none; has no background, and an <img> tag. DIV1 displays correctly with background, and DIV2 is not displayed as expected. I click a button that loads a picture, DIV1 is set to display: none and disappears, while DIV2 is set to display: block and appears with the picture where DIV1 was. ALL IS WELL. I click a second button that recals DIV1 by setting DIV2 to display: none and DIV1 to display: block, and PROBLEM: it shows ok except that the picture remains on the screen on top of DIV1??? I am not sure if DIV2 is still on top or if it is just the picture that remains??? It is as though IE(7) puts the img tag in a different context than its original (DIV2)? I would greatly appreciate a clue to get me out of this impass. Thank you.

  6. Hi! This is very helpful. However when I tried to implement it the html {height:100%} actually pushes down the content by 100% of the browser height… However if I take out height for html then the distance div will not appear!

    My html code is valid! I was wondering if anything can help me identity the issue with the html height.

  7. Perishable 2008/07/13 7:33 am

    Hi Emyyy, without an actual example to look at, it is difficult to determine the issue. Nonetheless, if it were me, I would begin with a document that contained exactly the code presented in the article. Make sure you can get that working first, and then tweak it to serve your specific needs. This will enable you to catch any modifications that might “break” the layout. I hope that helps! ;)

  8. linkdor web directory 2008/08/11 8:48 am

    Very good ideas, but we all have to be sure that it will look good on all explorers. It’s true that 90 percent of out visitors use IE and Mozilla but the remaining 10 will always have their own version of navigator, so we care about all of them no ?

  9. Very helpful article thanks heaps.

  10. Maloblanco 2008/09/01 2:40 am

    Hey Perishable ,

    Thank you very much for this tutorial. It has saved my ass on a current project at the studio!

    It’s really helpful. As in my project I’m using embedded flash, I went for “px” instead of “em” and it works smoothly.

    Cheers

  11. Excellent! Glad to hear the article is still useful! Thanks for the feedback :)

  12. Adedoyin Kassem 2008/10/06 3:08 am

    Hi there, nice tip here but i have one problem with this particular tutorial and it is the fact that this code does not work on Google chrome!
    Can you ix this please? I would be looking forward to your reply

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
SAC Pro: Unlimited chats.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.