Centering an Absolute Div in IE

Discussion in 'CSS' started by Doc Croc, Nov 11, 2008.

  1. #1
    Hi folks,

    I hope you can help. I'm trying to figure out how to center an absolute div tag. The following example code works in Firefox, Opera, Chrome etc. but not IE 7. It'll work in IE if I change the DIV to position:relative, but I don't want to do that - the tag has to be absolutely positioned.

    I also want to avoid using the left:50%; margin-left: -50px; fix, because of resizing issues that stem from it.

    Any help would be greatly appreciated.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    
    <style type="text/css">
    
    body {
    	text-align: center;
    	}
    
    .box {
    	position: absolute;
    	width: 100px;
    	left: 0; 
    	right: 0; 
    	margin: 0 auto;
    	}
    
    </style>
    
    </head>
    
    <body>
    
    <div class="box">
    Centered
    </div>
    </body>
    </html>
    Code (markup):
     
    Doc Croc, Nov 11, 2008 IP
  2. lektrikpuke

    lektrikpuke Well-Known Member

    Messages:
    297
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    113
    #2
    The easiest way to keep everything "relative" is to make the containing div relative (and make margin:0 auto; ). The containing div doesn't have to show anything. It's there to make sure everything inside it stays centered. Note: You still have to hack the CSS for IE ('cause it's a rogue). In the the html, you have to say the containing div is centered (align="center"), and sometimes even go so far as to say text-align: center;

    Any way, your div can then be centered absolute and it will stay in the same place regardless of resolution or window size. :eek:
     
    lektrikpuke, Nov 11, 2008 IP
  3. Doc Croc

    Doc Croc Peon

    Messages:
    34
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hey there,

    Thanks your help, lektrikpuke, I managed to get it working!

    Following your advice, I kept the .box tag the same, but added the following to body {position:relative; width:100px; margin: 0 auto; text-align: center;}

    Amazing - you wouldn't believe how long that's been bugging me! :)

    Cheers!
     
    Doc Croc, Nov 11, 2008 IP
  4. lektrikpuke

    lektrikpuke Well-Known Member

    Messages:
    297
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    113
    #4
    No problem. Thanks for helping me with my problem. :D
     
    lektrikpuke, Nov 11, 2008 IP
    Doc Croc likes this.
  5. mypsdtohtml

    mypsdtohtml Guest

    Messages:
    96
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #5
    margin: 0 auto;

    is the solution to center absolute in the browser in your XHTML CSS
     
    mypsdtohtml, Nov 13, 2008 IP