html - 在视口(viewport)中垂直和水平居中 HTML 元素的最佳方法是什么?

标签 html css html-table center centering

假设我想在我的视口(viewport)中心放置一个元素用作弹出消息。它应该满足以下条件:

  • 即使元素大小动态变化,元素也应在浏览器中保持居中(水平和垂直)
  • 如果调整浏览器大小,元素应保持居中
  • 不允许使用 Javascript
  • 仍适用于 IE7

有没有更好的方法可以在不求助于下面基于表格的解决方案的情况下实现这一目标?

<table style="position:absolute;width:100%;height:100%">
    <tr>
        <td align="center">
            <span id="centeredContent">I always remain centered</span>
        </td>
    </tr>
</table>

最佳答案

最好的解决方案(在我看来)是使用绝对定位将元素的左上角放置在 50%/50% 处,然后使用负边距将元素推回中心。唯一的缺点是您必须指定元素的宽度和高度。这是一个例子:

HTML:

​<div id="centerme">
    Hello, world!
</div>​

CSS:

​#centerme
{
    position: absolute;
    left: 50%;
    top: 50%;

    /* You must set a size manually */
    width: 100px;
    height: 50px;

    /* Set negative margins equal to half the size */
    margin-left​: -50px;
    margin-top: -25px;

    background-color: cornflowerblue;
}

这是 jsfiddle 上的演示:http://jsfiddle.net/UGm2V/


如果您确实需要居中内容具有动态高度,则有更高级的解决方案。请注意,它不能在旧的 IE 浏览器中运行。 HTML 如下所示:

<div id="outter-container">
    <div id="inner-container">
        <div id="centred">
            <p>I have a dynamic height!</p>
            <p>Sup!</p>
        </div>        
    </div>
</div>

外部容器需要覆盖页面的宽度和高度。它是一个具有绝对定位的 block 元素。
内胆其实是一张 table !这是由 display: table css 属性决定的。这里的好处是您实际上不需要任何表格 HTML。
#centred div 是最后一个必需的元素。它仍然覆盖 100% 的页面宽度和高度,但放置在其中的任何内容都将在垂直和水平方向上居中。这是您需要的 css,并附有解释:

/*
An outter container is needed because the table
won't cover the page width and height on it's own
*/
#outter-container
{
    position: absolute;
    top: 0px;
    right: 0px;
    bottom: 0px;
    left: 0px;
}

/*
The inner container is a table which is set to
cover the width and height of the page.
*/
#inner-container
{
    display: table;
    width: 100%;
    height: 100%;
}

/*
This table cell will cover 100% of the page width
and height, but everything placed inside it will
be placed in the absolute centre.
*/
#centred
{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

当然,这里还有一个 jsfiddle 演示:http://jsfiddle.net/N7ZAr/3/

关于html - 在视口(viewport)中垂直和水平居中 HTML 元素的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9669296/

相关文章:

javascript - 如何使用 JavaScript 控制台对现有 DOM 元素进行排序?

html - CSS Sprites - 在 IE 8 和 7 中不显示

php - 如何从 JSON 格式创建表或追加?

php - 将产品添加到数据库时添加日期/时间

html - 将参数传递给 liferay portlet

html - HTML 中的文件路径问题?

html - 用图像填充剩余的 div 高度

html - 在内联样式中将宽度设置为星号的目的是什么?

php - 如果该行中的某个单元格为空,如何隐藏整行?

HTML:IE9 标准模式在每个页面上打印 TFOOT