如何在没有绝对定位的情况下在身体元素内垂直和水平居中?

时间:2013-03-10 13:02:31

标签: css html centering

我已经阅读了无数关于垂直对齐和居中div的Q& A和博客帖子,但我无法让最简单的案例工作:直接在html体内的空20x20 div。

HTML:



 body
    {
        background-color:DarkGray;
        display:table;
    } 

    .box
    {
        background-color:black;

        display:table-cell
        margin:0, auto;    
        
        width:20px;
        height:20px;
    }

<body>
    <div class="box">
    </div>
</body>

 
   
&#13;
&#13;
&#13;

这是JSFiddle

3 个答案:

答案 0 :(得分:14)

display:tabledisplay:table-cell不好,远离它们。这是将div置于<body>内部的一种非常常见的方法。它将元素的顶部和左侧定位在body内的50%点,然后从widthheight中减去1/2 margin-topmargin-left

jsFiddle

.box
{
    background-color:black;
    position:absolute;
    left:50%;
    top:50%;
    width:20px;
    height:20px;

    margin-left:-10px; /* -1/2 width */
    margin-top:-10px; /* -1/2 height */
}

答案 1 :(得分:1)

首先,在margin样式中存在语法错误:

margin: 0, auto;

但应该是:

margin: 0 auto;

支持垂直定位应该是:

http://jsfiddle.net/olexander/8At93/387/

html, body {
    height: 100%;
}

.box {
    position: relative;
    top: 50%;
    margin: -10px auto; /* -height/2 */
    width: 20px;
    height: 20px;
}

此网站上有讨论Why not use tables for layout in HTML?

答案 2 :(得分:1)

Tyriar的代码绝对是最好的解决方案 永远记住要将margin-leftmargin-top设置为您希望居中的div宽度的一半,因为元素始终从它们的边而不是它们的中心对齐。