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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15322519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:18:13  来源:igfitidea点击:

How do I center vertically and horizontally a div inside the body element without absolute positioning?

csshtmlcentering

提问by circuitlego

I have read countless Q&A's and blog posts about vertically aligning and centering divs, but I cannot get the simplest case to work: an empty 20x20 div directly in the html body.

我已经阅读了无数关于垂直对齐和居中 div 的问答和博客文章,但我无法得到最简单的案例:直接在 html 正文中的空 20x20 div。

html:

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>

 
   

Here is the JSFiddle.

这是JSFiddle

回答by Daniel Imms

display:tableand display:table-cellare bad, stay away from them. Here is a very common way to center a divinside <body>. It positions the element's top and left sides at the 50% point within bodyand then subtract 1/2 the widthand heightfrom the margin-topand margin-left.

display:tabledisplay:table-cell坏的,远离他们。下面是一个居中一种很常见的方式div<body>。它定位元素的顶部和左侧的内50%的点body,然后减去1/2 width,并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>

回答by Olexander Ivanitskyi

First, there is a syntax error in margin style:

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

margin: 0, auto;

But should be:

但应该是:

margin: 0 auto;

With support of vertical positioning it should be:

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

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?

并且在这个站点上有一个讨论为什么不使用表格进行 HTML 布局?

回答by What Do Parrots Do

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

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