Center Absolute Position DIV

iStock_000015512331XSmall

Centering a div on the screen with absolute position is something may at first seem very complicated, but with a little thinking and simple addition to the position element you can easily center an absolute position div in the middle of the screen.

This can be helpful for creating a wrapper to contain and center the contents of your entire site on the page.

Lets say that you have a simple page like this:

<div id="xyz_main">
    <div id="xyz_header"> Header </div>
    <div id="xyz_body"> Body </div>

    <div id="xyz_footer"> Footer </div>
</div>

And you wish to center the ‘main’ div in the center of the page as an absolute position center div. You can do this by adding the following positional style attributes to the ‘main’ div:

#xyz_main {
    width: 140px;
    border: 1px solid #666666;
    text-align: left;
    position: absolute;
    top: 0px;
    left: 50%;
    margin-left: -70px;
}

By setting the left position to 50% it will set the div to start in the center of the screen. By adjusting the left margin by a value half of the size of the div we are centering, we can move the entire div to the left and place it directly in the center of the page.

Your page would now look something like this:


Header
Body content here…

That’s it! That is all you have to do to center an absolute position div on the page… Enjoy!







NOTE: I have added a new CSS Template Cheats section to the site. This new resource has even more compliant methods of centering DIVs.





About the author

Founder of Eos Designs and co-founder of iPrintEasy and a number of other web businesses - an entrepreneur with over 10 years of experience in Internet Marketing - Zach understands what it takes to be successful online and specializes in the development of advertising campaigns and marketing plans for start-ups.
  • http://jayalakmal.blogspot.com Lakmal

    Thanks a lot..
    I could also center align an absolutely positioned Div element. :-)
    It worked in FF 3.0.8 and in IE 7

  • Allan

    Thank. You.
    This has been killing me for a while since I was using the auto margin left and right method. Does not work in IE 7 with absolute.

  • alon

    thanks !!
    working good.

  • Pingback: CSS - transparent Backgrounds - UK Graphic Design Forums | UK Website Design Forums

  • Chris

    Thanks a lot! Works nicely, and very simple.

  • http://poochycat.com Catzie

    This is a BRILLIANT idea I never thought of. Thank you very much! It helps a lot. :D :D

    Catzie’s last blog post… Some changes…

  • matt

    You rock!

  • chris

    Brilliant!! This is exactly what I was looking for! So glad you posted this.

  • http://www.fusionit.com.my FusionIT.com.my

    Thank you very much for this information, it is extremely beneficial and cross browser compatible. We do look forward reading more of your posts.

  • http://www.greggblanchard.com Gregg Blanchard

    Brilliant! Works like a charm…been looking for a fix on this for a while!

    Gregg Blanchard’s last blog post… I’m Stumped: Can You Help?

  • Pingback: Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?

  • warren

    Did this and it F$%^&ED UP EVERYTHING THAT WAS NESTED INSIDE MY “CONTENT”!!! Now my content is about 100-200px off to the left of my large div depending on screen resolution

  • mike

    Thank you! This is a great tip!

  • Ryan Morales

    #content
    {
    width:50%;
    position:absolute;
    top:100px;
    left:25%;
    margin-left: -70px;
    }

    tested this in both firefox(3.x) and safari(3.x)

    why width:140px?
    why left: 50%?

  • http://jordanmooredesign.com/ Jordan Moore

    Hey guys,

    Where the width of the container element is unknown (eg a full page width) you need to tell the target element IE6.

    left:auto;

  • Nai

    I’ve got this working in IE6, IE7 and IE8. I thought it might be the lack of a proper DocType that was throwing others off, but that doesn’t seem to be the problem.

    Kudos on this solution!

  • http://www.questpartnership.co.uk Richard

    thanks so much – simple, clear and effective explanation! I just spent hours trying to work this out through various google searches. Very much appreciated!

  • Linus Forsell

    Works like a charm, thank you!

  • http://www.zachalig.com Zach

    Very nice. Thanks for the help

  • Nicodamus

    Hey this solution works great in IE8, Chrome, FF, Safari! I was having issues centering a div over a Myspace page (div.topheader) and my earlier code was working great in all browsers except for IE8! My particular issue was solved by setting the div to an actual width (not 100%), setting left to 50% as you do here, and then setting my margin-left to half of the width. Works like a charm! Thank you!

  • Raghu

    Thanks, Works good if we know the div size. How about for div’s for which we dont know the size….any ideas?

  • Shawn

    It floors me that the powers that be think that “rotate text” and “add drop shadow to text” features are more important for CSS than the most trivial positioning constructs. I’d love to live back in ’96 before dynamically generated content so I’d always know the exact widths of my elements… but I don’t. I appreciate that you’re breaking your back to make CSS ‘usable’ for static documents; I’m just pissed off. Keep up the good work, hopefully a day will come soon when CSS works. (I’ve been saying that for a long time… it’ll happen… right?… right?)

  • http://www.zubrag.com freelancer

    Thank you! I was thinking about javascript implementation, but your solution is much better.

  • Pingback: Great CSS Resources and Articles for Students | Resources for Web Development Students @ Robin's Blog

  • http://google.com Thomas

    if you don’t know the width of the div, you will need two divs:

    not tested:

    • http://google.com Thomas

      oh, my post got destroyed somehow, here is another try without tags lt/gt:

      div style=”position:absolute; top:50%; left:50%; border:2px solid #006;”

      div style=” background-color:#C60; margin:-25% 0 0 -50%; width:200px; height:100px; “>/div

      /div

  • http://ducatiadelaide.com.au Nicholas Reed

    using on ducatiadelaide.com.au thats I’m currently developing, very helpful.
    You have allowed me to smoothly place the main navigation in the center of the viewport with no problems! Thanks heaps!

    Nicholas Reed.

  • http://DerekHyams.com Derek Hyams

    oh my word, i was down to my last hair to pull out! many thanks!

  • http://www.tradeo.biz/ yMladenov

    Simple, standards-compliant and cross-browser. Thank you!!

  • http://www.naijaslangs.com Gozie

    Trust me Zach… u’re d Best! It works perfectly fine in IE7 and other browsers. I’ve been tryn 2 get dis for the past 8 months now! Thank you once again Zach.

  • http://www.megahard.co.cc salmanabbas007

    position:absolute;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    width: 99%;
    height: 99%;
    i used this and it worked in IE and FF

  • http://www.megahard.co.cc salmanabbas007

    I wanted to use on my website if someone has 800×600 res instead of 1024×768

  • http://www.thinkdave.com Dave

    Nice simple solution. Works perfectly in FF3.5, IE7 and IE78. But you probably already knew that…

  • http://www.harbourstudios.com Oliver Coquelin

    When you use this technique in Chrome it seems to cut square blocks out of the background to the right and to the bottom of the centralised div. Does anyone know a fix for this?

  • Susanne

    Deceptively simple!
    Thanks!

  • http://TheHypeFactor.com KrAzyChe3To

    This was exactly what I was looking for I was trying to get a Leaderboard Advertisement at the top of my page and I couldn’t get it centered after trying for 15 minutes. This helped me so much, thanks again!

  • adrianaleites

    and if the width of my container is variable conform the height?

    html:

    css:

    .main {
    height: 100%;
    background-color: black;
    margin: 0 auto;
    position: absolute;
    }

    My image is a square and i want its height 100% to fill the max-height of all screens. But i still want to get this centered horizontally. I’ve already tried to “align: center;” but didnt work. If any idea to solve this…

    Thanks in advance.

  • adrianaleites

    *html:

  • adrianaleites

    never mind! problem solved:

    .main {
    height: 100%;
    width: 100%;
    background-color: black;
    margin: 0 auto;
    position: absolute;
    }

    .image {
    margin-left: auto;
    margin-right: auto;
    display: table;
    }

    i created a class to my image and centered it to div. And set div dimensions for 100%x100%

    • Andy Ulumudin

      Great, thank you for your sharing. It’s works

  • adrianaleites

    seems like IE doesn’t like “display: table”. So we have to add “text-align: center;” to main.

  • Maya

    brilliant, thanks!

  • http://www.vieswebdesign.com HuwD

    If you use Grimm’s CSS code:

    #xyz_main {
    width: 140px;
    border: 1px solid #666666;
    text-align: left;
    position: absolute;
    top: 0px;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
    }

    The IE7 problem can be overcome with the following Javascript function;

    function centrePage() {
    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    var arrVersion = b_version.split(“;”);
    var versionStr = “”;
    var i;
    for (i = 0; i < arrVersion[1].length; i++) {
    if (isNaN(arrVersion[1][i]) == false) {
    versionStr = versionStr + arrVersion[1][i];
    }
    else if (arrVersion[1][i] == ".") {
    versionStr = versionStr + arrVersion[1][i];
    }
    }
    var version = parseFloat(arrVersion[1].replace("MSIE ", ""));
    var contDv = document.getElementById("xyz_main");

    if ((browser == "Microsoft Internet Explorer") && (version 0) {
    contDv.style.left = lSpace;
    }
    }
    }

    you then just need to call this function with “onload” and “onresize” in the body tag like so:

    and it will compensate if the user is using IE7 or earlier.

    Hope this helps

  • Jona

    Hello, It worked perfect for me but I have litle a problem. I have a table above the footer, and it was perfect until I started to fill the table with information, the cell went dont through the footer to the end of the page, the footer didn’t contain the above information. Tha table just didn’t care about the footer. How can I fix this?

  • http://teamnos.info naveen

    works great!!
    thank you

  • magnolia

    Really nice! I’ve been looking for a solution for hours now.
    Thanks a lot!

  • http://www.sikosoft.com Lev

    Kinda surprised that no one has pointed this out yet (or maybe I missed it) – Do all of you really do your layouts in pixels and never want to vertically align something?

    It’s a nice solution for people who do *fixed-pixel* layouts, but folks who do elastic layouts (based on percentages, which is often preferred for presentation on a variety of screen resolutions) this does NOT work WITH HEIGHTS. It does still work with percentages and widths, but from all my testing, the results are very unexpected when using something like:

    height: 90%;
    top: 50%
    margin-top: -45%;

  • dan

    thanks!

  • http://www.brianshoff.com Shoffy

    Genius man. Absolute genius (pun intended).

  • http://www.teddybearfriends.co.uk Kevin

    This works great in positioning the content.

    However, if I want to use a background color or image it won't display unless I use a height – the border currently appears as a 2px high line at the top of the page??

  • http://moonlight-webservices.com Luke

    Brilliant idea mate, thanks! I've always gotten stuck and annoyed trying to accomplish this effect.

  • TJL

    It seems to work fine in full screen, but when you resize the browser, part of the page will be hidden.

Powered by WordPress | Privacy Policy | Web Design Miami