How to Center a Table inside a Div using CSS

If you have been looking for a simple way to center a table inside a div, then here it is

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title></title>
 <style type="text/css">
 #divOne
 {

 width:400px; 
 text-align:center; 
 border:dotted 1px black; 
 }
 #tblOne
 {
 width:200px; 
 margin:0 auto
 border: solid 1px black; 
 }
 </style>
</head>
<body>
 <div id="divOne">
 <table id="tblOne">
<tr>
<td>R1C1</td>
 <td>R1C2</td>
 <td>R1C3</td>
 </tr>
 <tr>
 <td>R2C1</td>
 <td>R2C2</td>
 <td>R2C3</td>
 </tr>
</table>
</div>
</body>
</html>

I have seen lot of people missing out on the margin:auto property. Setting margin to auto is the correct way to center a table and works in ‘most’ of the browsers. The border is just for illustration purposes and is not required.

OUTPUT

Advertisements