How to position a table at the center of div horizontally & vertically

We can set a image as background image of a <div> like:

<style>
    #test { 

        background-image: url(./images/grad.gif); 
        background-repeat: no-repeat;
        background-position: center center; 

        width:80%; 
        margin-left:10%; 
        height:200px; 
        background-color:blue;

    }

</style>

<div id="test"></div>

I need to set a table at the center of a <div> horizontally & vertically. Is there a cross-browser solution using CSS?


Centering is one of the biggest issues in CSS. However, some tricks exist:

To center your table horizontally, you can set left and right margin to auto:

<style>
  #test {
    width:100%;
    height:100%;
  }
  table {
    margin: 0 auto; /* or margin: 0 auto 0 auto */
  }
</style>

To center it vertically, the only way is to use javascript:

var tableMarginTop = Math.round( (testHeight - tableHeight) / 2 );
$('table').css('margin-top', tableMarginTop) # with jQuery
$$('table')[0].setStyle('margin-top', tableMarginTop) # with Mootools

No vertical-align:middle is possible as a table is a block and not an inline element.

Edit

Here is a website that sums up CSS centering solutions: http://howtocenterincss.com/


Here's what worked for me:

#div {
  display: flex;
  justify-content: center;
}

#table {
  align-self: center;
}

And this aligned it vertically and horizontally.


To position horizontally center you can say width: 50%; margin: auto;. As far as I know, that's cross browser. For vertical alignment you can try vertical-align:middle;, but it may only work in relation to text. It's worth a try though.


Just add margin: 0 auto; to your table. No need of adding any property to div

<div style="background-color:lightgrey">
 <table width="80%" style="margin: 0 auto; border:1px solid;text-align:center">
    <tr>
      <th>Name </th>
      <th>Country</th>
    </tr>
    <tr>
      <td>John</td>
      <td>US </td>
    </tr>
    <tr>
      <td>Bob</td>
      <td>India </td>
    </tr>
 </table>
<div>

Note: Added background color to div to visualize the alignment of table to its center