How to horizontal & vertical center a div?

Tattat picture Tattat · Dec 1, 2010 · Viewed 7.1k times · Source

Here is the source code:

<div id = "outer">
     <div id="top">
     ....
     </div>

     <div id="inner">
     ....
     </div>

     <div id="bottom">
     ....
     </div>     
</div>

I would like to know How to make the div (id inner), horizontal & vertical center? I can horizontal center, but can't make a vertical center... Thank you.

Answer

skajfes picture skajfes · Dec 1, 2010

If you know the dimensions of the inner div you can use CSS.

#outer {
    position: relative;
}

#inner {
    position: absolute;
    width: 200px;
    height: 200px;
    left: 50%;
    top: 50%;
    margin-top: -100px;
    margin-left: -100px;
}

There are other options using display: table-cell and vertical-align: middle etc.

Other options include JavaScript to dynamically determine the dimensions of the inner div and set the negative margins like above.