如何使屏幕中心(垂直和水平)居中

时间:2011-09-17 14:11:03

标签: html html-table

我有这些代码块:

<table border="1px">
<tr>
<td>
my content
</td>
</tr>
</table>

我想把我的桌子放在屏幕的中央(垂直和水平)。

Here is a demo

我该怎么做?

8 个答案:

答案 0 :(得分:16)

水平定心很容易。您只需将两个边距设置为“自动”:

table {
  margin-left: auto;
  margin-right: auto;
}

垂直居中通常是通过将父元素显示类型设置为table-cell并使用vertical-align属性来实现的。假设你的桌子周围有<div class="wrapper">

.wrapper {
  display: table-cell;
  vertical-align: middle;
}

可在http://www.w3.org/Style/Examples/007/center

上找到更详细的信息

如果您需要支持旧版本的Internet Explorer (我不知道什么版本的这个奇怪且很少使用的浏览器;-))那么您可能想要{{3}有关更多信息,例如:search the web(只是第一次点击,似乎提到了IE)

答案 1 :(得分:15)

这会修复屏幕上的框死点:

<强> HTML

<table class="box" border="1px">
    <tr>
        <td>
            my content
        </td>
    </tr>
</table>

<强> CSS

.box {
    width:300px;
    height:300px;
    background-color:#d9d9d9;
    position:fixed;
    margin-left:-150px; /* half of width */
    margin-top:-150px;  /* half of height */
    top:50%;
    left:50%;
}

查看结果

  

http://jsfiddle.net/bukov/wJ7dY/168/

答案 2 :(得分:5)

我认为这应该可以解决问题:

<table border="1px" align="center">

根据http://w3schools.com/tags/tag_table.asp,这已被弃用,但请尝试一下。如果它不起作用,请选择网站上提到的样式。

答案 3 :(得分:5)

用于水平对齐(无CSS)

只需在表格标记

中插入对齐属性即可
<table align="center"></table

答案 4 :(得分:3)

我一直在使用这个小作弊。你可能会喜欢它。将您想要居中的表嵌套在另一个表中:

<table height=100% width=100%>
<td align=center valign=center>

(在此处添加表格)

</td>
</table>

对齐和valign将表格准确地放在屏幕中间,无论发生了什么。

答案 5 :(得分:0)

This guy有我们正在寻找的魔杖,伙计。

引用他的回答:

  

只需添加“position:fixed”,即使向下滚动,它也会保持在视图中。在http://jsfiddle.net/XEUbc/1/

看到它
#mydiv {
    position:fixed;
    top: 50%;
    left: 50%;
    width:30em;
    height:18em;
    margin-top: -9em; /*set to a negative number 1/2 of your height*/
    margin-left: -15em; /*set to a negative number 1/2 of your width*/
    border: 1px solid #ccc;
    background-color: #f3f3f3;
}

答案 6 :(得分:0)

我在HTML5中尝试了上面的align属性。它不受支持。我还尝试了flex-align和vertival-align与样式属性。仍然无法将TABLE放在屏幕中央。 以下样式放置表位于水平居中。

风格= “保证金:汽车;”

答案 7 :(得分:0)

一种在水平和垂直方向上将高度和宽度未知的任何元素居中的方法:

table {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

See Example