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

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: