Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

centering a table

Status
Not open for further replies.

davikokar

Technical User
May 13, 2004
523
IT
Hallo,
I have a table with a specific size (775px) and I want it to be centered in the screen. With normal bad html is work like this:

<table align="center" ...>

but I'm rewriting the site using css and I cannot find a similar way to achieve this. The only thing I could do is inserting the table in a 100% wide cell and then setting the text-align of this cell to center...
Does someone know if there is a better way?
 
Unfortunately, you can't, because of the limitations of Internet Explorer. The correct syntax for centering an element is changing margin-right and margin-left to auto. But IE does not support that, so you have to wrap it up in another element that is centering its contents:
Code:
<div style="text-align: center;">
  <table width="770" style="margin-left: auto; margin-right: auto;">
...
  </table>
</div>
This should work in latest Mozilla, NN, Opera and IE browsers.
 
I use:

Code:
<center>
</center>

around the whole table... might be low tech, but it works like a charm.

deletion mistake
no I can't recover that
you didn't save it

-Shrubble
 
problem there is <center> is a deprecated tag and as such may not be supported in future browsers (or even some current ones)



Chris.

Indifference will be the downfall of mankind, but who cares?
 
Using CSS to center your table works fine as long as your DOCTYPE is set correctly. See the code below. Tested in MSIE 6 and Mozilla 1.7b

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

<html>
<head>
	<title></title>
	<style type="text/css">
		body {
			margin: 0;
			padding: 0;
		}
		
		table {
			width: 775px;
			margin-left: auto;
			margin-right: auto;
			border: 1px solid red;
			padding-bottom: 0.5em;
			padding-top: 0.25em;
			margin-top:1em;
			background-color: Aqua;
		}
		
		td {
			border: 1px solid blue;
			background-color: silver;
			color: Black;
			text-align: center;
		}
		
		th {
			border: 1px solid purple;
			background-color: Yellow;
		}
	</style>
</head>

<body>
<table>
<tr>
<th colspan="3">Is this centered</th>
</tr>
<tr>
<td>Centered?</td>
<td>No</td>
<td>Yes</td>
</tr>
</table>


</body>
</html>

Ken Robinson
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top