http://www.iteye.com/topic/765150 提及该问题。做个分析记录如下:
文中引介了几个解决方案
1)hack方法,IE和FF显示正常,但是chrome,opera, safari不能正常显示了,并且hack方法不建议使用。
2)在div外加center标签,显示效果OK,但不符合布局规则并且是不建议使用的标签。
3)经测试,效果完美。
<style type="text/css">
.container {border: solid 1px blue; text-align:center;}
table {border: solid 1px red; margin-left:auto; margin-right:auto; }
td {border: solid 1px green;}
</style>
<div class=container>
<table>
<tr><td>Text</td></tr>
</table>
</div>
经仔细分析,这个问题是因为table,thead, tbody, tfooter, tr,th, td都有默认的display样式导致,而IE与其他浏览解析不同。
CSS2下display相关属性值
display : none | inline | block | list-item | run-in | compact | marker | table |
inline-table| table-row-group | table-header-group | table-footergroup |
table-row | table-column-group | table-column | table-cell | table-caption
以下代码就会出现与使用table同样的问题
<style type="text/css">
.container {border:solid 1px blue; text-align:center;}
.content {border:solid 1px red; display:table;}
</style>
<div class="container">
<div class="content">test</div>
</div>
其他不完美的解决方式:
1)如果简单要让table居中,可以设置table的display:inline。
问题:IE、chrome、safari显示OK;firefox、opera显示有问题。
因为inline不能设置宽度和高度,浏览器对inline的解析效果不同。
<style type="text/css">
.container{border:solid 1px blue; text-align:center;}
table {border:solid 1px red; display:inline;}
td {border:solid 1px green; }
</style>
<div class="container">
<table>
<tr><td>Text</td></tr>
</table>
</div>
2)设置table宽度100%,并让td的text-align:center;
问题:td中的文本只是相对table居中。
<style type="text/css">
.container{border:solid 1px blue; text-align:center;}
table{border:solid 1px red; width:100%;}
td {border:solid 1px green; text-align:center;}
</style>
<div class=container>
<table>
<tr><td>Text</td></tr>
</table>
</div>