Search code examples
csshtml-tablealignmentvertical-alignmentcentering

Centerize table vertically and horizontally in div


You may think it was duplicated, but I don't thinks so, because I'm talking about tables not images!

I tried to set a table in center of div horizontally and vertically with the below codes. The codes work fine for images but when I put a table instead of image, it seems it can not see the tables and then put the span size to 100% and table display below of div not in center of div.

Codes:

<style>
.wraptocenter {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width:155px;
    height: 160px;
    background-color:#999;
    display: block;
}
.wraptocenter * {
    vertical-align: middle;
}

.wraptocenter span {
    display: inline-block;
    height: 100%;
    width: 1px;
}

</style>
<!--[if lt IE 8]><style>
.wraptocenter span {
    display: inline-block;
    height: 100%;
}
</style><![endif]-->
<div class="wraptocenter">
    <span></span>
    <table border="1" width=" 70%">
        <tr height="10px">
            <td width="10px" height="10px"></td>
            <td width="10px" height="10px"></td>
        </tr>
        <tr height="10px">
            <td height="10px"></td>
            <td height="10px"></td>
        </tr>
    </table>
</div>

If you put a images every thing work fine but for tables NOT!


Solution

  • See http://jsfiddle.net/FW2Af/

    Your code only center elements with display:inline-block, such as images. But a table has display:table.

    Then, you can solve it creating a div with display:inline-block which contains your table.

    And if you want table's width to be 70% of wraptocenter`s width:

    • Set width:100% to the table
    • Set width:70% to the container div.

    Moreover, you have width="10px" on the top cells. If the table has a width of 70%, that's nonsense.

    Edit:

    I have fixed for IE 7 (and before), because if you set display:inline-block to an element which is a block, it continues being a block, so you have to set diplay:inline in order to make it be display:inline-block:

    <!--[if lt IE 8]><style>
    .wraptocenter>div{
        display:inline;
    }
    </style><![endif]-->
    

    Moreover, the white spaces between the <span> and the <div> are shown on some browsers, so the table isn't completely centered.

    The solution is:

    .wraptocenter {
        font-size:0;
    }
    .wraptocenter>div{
        font-size:16px; /* Or whatever you want */
    }
    

    (Font: https://stackoverflow.com/a/8902198/1529630, it's a great idea because in this case using floating would break the centering)

    See it here: http://jsfiddle.net/FW2Af/2/

    Edit 3:

    You say that on IE 8 nothing is shown. For me it works but instead of a black border, it's white. Fixed here: http://jsfiddle.net/FW2Af/3/

    .wraptocenter td{
        border:1px solid black;
    }