如何在没有绝对定位的情况下将div垂直和水平居中于body元素内? [英] How do I center vertically and horizontally a div inside the body element without absolute positioning?

查看:65
本文介绍了如何在没有绝对定位的情况下将div垂直和水平居中于body元素内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了无数有关垂直对齐和居中div的问答和博客文章,但我无法获得最简单的方法:直接在html正文中使用一个20x20的div作为空值.

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.

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 .

推荐答案

display:table display:table-cell 不好,请远离它们.这是在< body> 内将 div 居中的一种非常常见的方法.它将元素的顶部和左侧放置在 body 内的50%点处,然后从减去 width height 的1/2> margin-top margin-left .

display:table and display:table-cell are bad, stay away from them. Here is a very common way to center a div inside <body>. It positions the element's top and left sides at the 50% point within body and then subtract 1/2 the width and height from the margin-top and margin-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>

这篇关于如何在没有绝对定位的情况下将div垂直和水平居中于body元素内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆