I have searched a lot for centering a div, both horizontally and vertically, this is the method given everywhere:

div {
position:fixed;
top:50%;
left:50%;
margin-left:(div width/2)
margin-top: (div height/2)
}

I just found a new solution to centering a div, both horizontally and vertically, by wrapping it inside a table. I've tested it in ie7 and above, plus other browsers.

Here is an example : http://jsbin.com/ocenok/2/

I was wondering that the first method is found everywhere on the internet, SO, etc. and requires beforehand knowledge of width and height, or is usually calculated via Javascript.

The table approach seems flawless, and requires neither javascript, nor fixed height/width.

Are there any drawbacks to the table approach ?

(I do not know the height/width of the div that I want to center.)


Update (To make my question clearer) :

I myself hate using tables for non-tabular/layout data.

  1. I know that what I want can easily be achieved using Javascript.
  2. I figured I can achieve this using display:table, killing IE7 support.

But what I'm trying to understand is, that when I can achieve this using a single <table> element, what are the drawbacks, if any.

Checking Answers here and on similar questions, no one has recommended this method, even though it uses all valid HTML elements and syntax and rules.

If everyone is recommending to use javascript to handle presentation, even though it is easily possible using CSS, it must have some drawbacks.


Code :

  <table>
    <tr>
        <td>
            <div>This is div that needs to be centered.</
Edit
Report