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

前端之家收集整理的这篇文章主要介绍了在视口中垂直和水平居中HTML元素的最佳方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我想在视口的中心放置一个元素作为弹出消息.它应该满足以下要求:

>即使元素大小动态变化,元素也应在浏览器中保持居中(水平和垂直)
>如果调整浏览器大小,元素应保持居中
>不允许使用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>

外部容器需要覆盖页面的宽度和高度.它是具有绝对定位的块元素.
内部容器实际上是一张桌子!这是由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/

原文链接:https://www.f2er.com/html/226568.html

猜你在找的HTML相关文章