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

问题描述 投票:3回答:3

这个问题在这里已有答案:

我已经阅读了关于垂直对齐和居中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>

 
   

这是JSFiddle

css html centering
3个回答
14
投票

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

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
投票

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


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?

© www.soinside.com 2019 - 2024. All rights reserved.