<div>元素在页面中垂直和水平的最佳方法?

我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?


当前回答

是浏览器支持的,使用翻译功能强大。

position: absolute;
background-color: red;

width: 70%;     
height: 30%; 

/* The translate % is relative to the size of the div and not the container*/ 
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);

其他回答

如果你正在研究新的浏览器(IE10+),

然后你可以使用transform属性在中心对齐一个div。

<div class="center-block">this is any div</div>

这个的css应该是:

.center-block {
  top:50%;
  left: 50%;
  transform: translate3d(-50%,-50%, 0);
  position: absolute;
}

这里的问题是,您甚至不必指定div的高度和宽度,因为它会自行处理。

同样,如果你想把一个div放在另一个div的中心,那么你可以指定外部div的相对位置,然后这个CSS开始为你的div工作。

工作原理:

当您将left和top指定为50%时,div将位于页面的右下四分之一,其左上端固定在页面的中心。 这是因为,左/顶部属性(当以%给出时)是基于外部div(在您的情况下,窗口)的高度计算的。

但是transform使用元素的高度/宽度来决定转换,因此div将向左移动(50%宽度)和向上移动(50%高度),因为它们是以负号给出的,因此将其对齐到页面的中心。

如果你必须支持旧的浏览器(抱歉,包括IE9),那么表格单元格是最流行的方法。

使用Flex-box在我看来:

#{母公司 显示:flex; justify-content:中心; 对齐项目:中心; } < div id = "父" > <div id="child">Hello World!< / div > < / div >

您可以看到,只有三个CSS属性可以用于将子元素垂直和水平居中。显示:flex;通过激活Flex-box display来完成主要部分,justify-content: center;将子元素垂直居中并对齐-items: Center;水平居中。为了看到最好的结果,我只添加了一些额外的样式:

#{母公司 显示:flex; justify-content:中心; 对齐项目:中心; 身高:500 px; 宽度:500 px; 背景:黄色; } #孩子{ 宽度:100 px; 身高:100 px; 背景:银色; } < div id = "父" > <div id="child">Hello World!< / div > < / div >

如果你想了解更多关于Flex-box的知识,你可以访问W3Schools, MDN或CSS-Tricks获取更多信息。

请使用以下CSS属性水平和垂直居中对齐元素。这对我来说很有效。

div {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0px;
  margin: auto;
  width: 100px;
  height: 100px;
}

抱歉回复晚了 最好的办法是

  div {
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -100px;
    }

上边距和左边距应该根据你的div框大小

解决方案

仅使用两行CSS,利用Flexbox的神奇力量

.parent { display: flex; }
.child { margin: auto }