Using CSS to Absolutely Center Align a DIV

 

 

For those of you looking for the easiest way to absolutely center align a DIV using CSS only, and avoiding all of those really messy tables, whilst also wanting to fluidity in the design, please use the following code:

#container {
position: absolute;
left: 50%;
top: 50%;
width:560px;
height:380px;
margin-left: -280px; /* MUST UPDATE TO MATCH HALF THE WIDTH */
margin-top: -190px;  /* MUST UPDATE TO MATCH HALF THE HEIGHT */
}

Please note that if you change the width and height of the DIV, you must also change the margin left and top so that they exactly match half the size of the height and width. This can be avoided using percentages, but Internet Explorer does not accept percentages in height values, so to be truly cross-browser compatible, you need to do things manually for now, that is; until our up-coming DIVx widget has finished being baked!


 

 


  1. Widget Pi » Blog Archive » Absolutely Center Align a DIV using CSS UNITED STATES WordPress 2.2.1 30.08.07 / 10pm

    [...] Center Align a DIV using CSS This can be achieved with 7 simple CSS Statements, as seen in the full article we recently [...]

  2. Jerson Maglasang PHILIPPINES Windows XP Mozilla Firefox 2.0.0.9 23.11.07 / 7pm

    Try my simple solution on Centering Div:

    Horizontal Centering:


    #container{ margin-left:25%;margin-right:25%; }


    Vertical Centering:


    #container{ margin-top:25%;margin-bottom:25%:}

    Tested and Works on IE, Firefox, and Safari

  3. Genuine Administrator MALAYSIA Windows XP Mozilla Firefox 2.0.0.9 23.11.07 / 8pm

    We were under the impression that percentages in HEIGHT did not work in Internet Explorer, which is where all the trouble started….?

    Nonetheless, thanks for dropping by and leaving your two cents worth…

  4. Idetrorce UNITED STATES Windows Server 2003 Internet Explorer 7.0a1 15.12.07 / 6pm

    very interesting, but I don’t agree with you
    Idetrorce

  5. at SLOVAKIA Mac OS X Mozilla Firefox 2.0.0.12 18.03.08 / 2pm

    this is long, not well working and not relative,
    the position: relative; margin: auto; solves all your problems

  6. Genuine Administrator MALAYSIA Windows XP Mozilla Firefox 2.0.0.12 18.03.08 / 4pm

    Great feedback - thanks for supplying us with an example so we can make more sense of your suggestions…

    Very constructive indeed… :-)

Have your say




Safari hates me