HTML - 垂直对齐表格

4

可能是重复问题:
如何在CSS中垂直对齐表格

我想把我的表格放在页面正中间。水平对齐很容易,只需要使用

<table align="center"></table>

但是它不允许这样做:
<table align="center" valign="center">

我也无法将valign放在div中,因为它不是一个有效的属性。

我的想法是让单元格占据整个页面,然后使用:

<Table align="center" width="100%">
<tr><td valign="middle" height="100%"></td></tr>
</table>

但是,这也不起作用,因为我的<td>没有占据整个页面。当我将其高度设置为100%时,它仅占据必要的空间。
有什么想法吗?CSS代码也会很有帮助。

2
这并非不可能,但每种解决方案都存在问题。诚然,这是 CSS 的一个缺点,如果 W3C 能提出垂直居中问题的标准解决方案,那将是很棒的。 - Ryan Kinal
来自我们的朋友tutorialzine.com http://demo.tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/demo.html - Catfish
2个回答

3

http://www.pmob.co.uk/pob/vertical-center1.htm

点击上述链接后,右键打开页面并查看源代码。

你会注意到,IE使用条件注释(如果你不习惯它们,这可能很棘手)。他们在代码的第48行获取窗口高度,并将框放置在当前窗口高度的50%处,因此即使调整大小也可以使用。

对于其他浏览器,他们使用position、valign和text align的组合来实现所需的效果。

希望这有所帮助!


2

如果将对象的定位设置为绝对定位,它就能正常工作。

这里有一个例子(我只在Safari上尝试过):

<html>
  <head>
    <title>Dead Center</title>
    <style type="text/css">
      .dead_center {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        width: 30%;
        height: 30%;
        margin: auto;
        background-color: green;
      }
    </style>
  </head>
  <body>
    <table class="dead_center">
      <tr>
        <td>My centered table</td>
      </tr>
    </table>
  </body>
</html>

无需使用任何已弃用的属性,如align。


再添加19个表格行,它就不再居中了。 - Gert Grenander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接