5

我已经阅读了无数关于垂直对齐和居中 div 的问答和博客文章,但我无法让最简单的情况起作用:直接在 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

4

3 回答 3

21

display:table并且display:table-cell是坏的,远离他们。div这是使内部居中的一种非常常见的方法<body>。它将元素的顶部和左侧定位在 50% 点内body,然后从 and 中减去and的width1/2 。heightmargin-topmargin-left

.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 */
}
<body>
  <div class="box">

  </div>
</body>

于 2013-03-10T13:06:04.950 回答
2

首先,边距样式存在语法错误:

margin: 0, auto;

但应该是:

margin: 0 auto;

在支持垂直定位的情况下,它应该是:

html,
body {
  background-color: DarkGray;
  height: 100%;
}

.box {
  position: relative;
  top: 50%;
  margin: -10px auto;
  /* -height/2 */
  width: 20px;
  height: 20px;
  background-color: black;
}
<body>
  <div class="box">
  </div>
</body>

And there is a discussion on this site Why not use tables for layout in HTML?

于 2013-03-10T13:10:09.240 回答
1

Tyriar's code is definitely the best solution.
Always remember to set the margin-left and margin-top to half the width of the div you wish to center, as elements always align from their sides and not their center.

于 2013-03-10T14:00:54.590 回答