Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a table of the screen (vertically and horizontally)

I have these code block:

<table border="1px">
<tr>
<td>
my content
</td>
</tr>
</table>

I'd like to show my table in the center of the screen (vertically and horizontally).

Here is a demo.

How can I do that?

like image 862
cafu Avatar asked Sep 17 '11 14:09

cafu


2 Answers

Horizontal centering is easy. You just need to set both margins to "auto":

table {
  margin-left: auto;
  margin-right: auto;
}

Vertical centering usually is achieved by setting the parent element display type to table-cell and using vertical-align property. Assuming you have a <div class="wrapper"> around your table:

.wrapper {
  display: table-cell;
  vertical-align: middle;
}

More detailed information may be found on http://www.w3.org/Style/Examples/007/center

If you need support for older versions of Internet Explorer (I do not know what works in what version of this strange and rarely used browser ;-) ) then you may want to search the web for more information, like: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html (just a first hit, which seems to mention IE)

like image 73
Arsen7 Avatar answered Sep 27 '22 19:09

Arsen7


This fixes the box dead center on the screen:

HTML

<table class="box" border="1px">
    <tr>
        <td>
            my content
        </td>
    </tr>
</table>

CSS

.box {
    width:300px;
    height:300px;
    background-color:#d9d9d9;
    position:fixed;
    margin-left:-150px; /* half of width */
    margin-top:-150px;  /* half of height */
    top:50%;
    left:50%;
}

View Results

http://jsfiddle.net/bukov/wJ7dY/168/

like image 40
Andres Ilich Avatar answered Sep 27 '22 19:09

Andres Ilich