Search code examples
csshtmlalignment

align a variable width div in the center


Appologies for a duplicate question, but none of the answers to the other questions seem to fix my problem. I would like to align a div in the center of the page. The div must only be as wide as the content inside it. It will be used as a modal popup. I have setup a jsFiddle here: http://jsfiddle.net/PDzNj/11/

The div aligns its left side in the middle and not the center of the div (which is the desired effect)

Thank you in advance for any help


Solution

  • One option is to emulate a table with the <div>'s surroundings.

    <div class='outer'>
        <div class='inner'>
            <div class='thebox'>Contents</div>
        </div>
    </div>
    

    And then use the CSS:

    div.outer {
        display:table;
        width:100%; //Or however wide you want the container to be
    }
    div.inner {
        display:table-cell; //This allows the use of vertical-align
        vertical-align:middle;
        text-align:center;
        width:100%;
    }
    div.thebox { //Your variable-width container
        display:inline-block; //Makes it obey text-aligning.
    }
    

    You can of course add height values as needed. This is neater, CSS wise, than making it relative, or using margins, and also disrupts the surroundings less.