【问题标题】:How do I center vertically and horizontally a div inside the body element without absolute positioning? [duplicate]如何在没有绝对定位的情况下将主体元素内的 div 垂直和水平居中? [复制]
【发布时间】:2023-03-13 08:41:01
【问题描述】:

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

【问题讨论】:

标签: css html centering


【解决方案1】:

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

.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>

【讨论】:

  • 因为没有它们你可以做任何事情,所以它们被设计为仅用于表格单元格。他们可以做的一件事我认为没有他们你就无法做到,那就是垂直居中多行文本。
【解决方案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>

并且本站有讨论Why not use tables for layout in HTML?

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 1970-01-01
      • 2013-05-21
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      相关资源
      最近更新 更多