none
Horizontal center align multiple divs RRS feed

  • Question

  • I have a container div (#div1), which contains 5 child divs (#div2, #div3, #div4, #div5, #div6) contained inside it.

    The code is something like this:

     

    <div id="div1">

    <div id="div2">Content2</div>

    <div id="div3">Content3</div>

    <div id="div4">Content4</div>

    <div id="div5">Content5</div>

    <div id="div6">Content6</div>

    </div>

     

    The Content2,3,4,5,6 are all of different length.

    I want to align the 5 child divs (#div2, #div3, #div4, #div5, #div6) horizontally in one row inside the container #div1, such that the vacant space inside #div1 gets uniformly distributed between the child divs and the child divs become uniformly aligned in the "center".

     

    The main code for all child divs is (id no is the only thing changed to 3,4,5,6 etc)

     

    #div2{

    width: 23%;
    position: relative;

     

    margin:0px auto;

     

    white-space:normal;
    *display: inline;
    _display: inline;
    *margin: 0 2px 0 2px;

     

    display:INLINE-block;
    float:none;

    }

     

    The main code for container #div1 is

    #div1{

    margin:0px auto;

    width:98%;
    text-align:center;
    vertical-align:top;
    white-space:nowrap;
    position:relative;
    display:block;
    float:none;
    }

     

    However the above code only centers the child div on localhost in IE and Chrome Browser. However on the remote production server it aligns all child divs in one row only in Chrome browser. In IE9, it aligns all the child divs in one single column below one another instead of in one row as shown when hosted on localhost.

    If we change float to left or right for child div, no centering takes place and instead all the child divs align to one side. If the display property of child div is changed to block, the centering fails even on localhost. If the display is changed to inline, the div width becomes 100% automatically and it occupies the complete with of container.

    Can some one advise on how to ensure uniform horizontal alignment of all child divs in one row on localhost as well as actual remote site server on IE (>=IE6, all other browsers also). I would prefer if display:inline-block is also avoided (display:block or inline is preferred) as it may not be supported in earlier browsers.

    • Edited by S N Tuesday, December 6, 2011 4:46 PM
    Tuesday, December 6, 2011 3:40 PM

Answers