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

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


当前回答

这里还有一个方法(防弹),利用“display:table”规则:

标记

<div class="container">
  <div class="outer">
    <div class="inner">
      <div class="centered">
        ...
      </div>
    </div>
  </div>
</div>

CSS:

.outer {
  display: table;
  width: 100%;
  height: 100%;
}
.inner {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.centered {
  position: relative;
  display: inline-block;

  width: 50%;
  padding: 1em;
  background: orange;
  color: white;
}

其他回答

如果你正在使用JQuery,你可以使用.position();

<div class="positionthis"></div>

CSS

.positionthis {
    width:100px;
    height:100px;
    position: absolute;
    background:blue;
}

Javascript JQuery ()

$(document).ready(function () {
    $('.positionthis').position({
        of: $(document),
        my: 'center center',
        at: 'center center',
        collision: 'flip flip'
    });
});

http://jsfiddle.net/vx9gV/

尽管当OP问这个问题时,这并没有起作用,但我认为,至少对于现代浏览器来说,最好的解决方案是使用display: flex或伪类。

你可以在下面的小提琴中看到一个例子。 这是更新后的小提琴。

对于伪类,一个例子可以是:

.centerPseudo {
    display:inline-block;
    text-align:center;
}

.centerPseudo::before{
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
    width:0px;
}

display: flex的用法,根据css-tricks和MDN说明如下:

.centerFlex {
  align-items: center;
  display: flex;
  justify-content: center;
}

flex还有其他可用的属性,在上面提到的链接中解释了这些属性,并提供了进一步的示例。

如果你必须支持不支持css3的旧浏览器,那么你可能应该使用javascript或其他答案中显示的固定宽度/高度解决方案。

在父元素上使用display:grid并将margin:auto设置为居中元素即可:

请看下面的片段:

html,身体{ 宽度:100%; 高度:100%; 保证金:0; 填充:0; } .container { 显示:网格; 高度:90%; 背景颜色:蓝色; } .content { 保证金:汽车; 颜色:白色; } < div class = "容器" > <div class="content"> cented div here</div> < / div >

我知道我迟到了,但是这里有一种方法可以将一个维度未知的div集中在一个维度未知的父元素中。

风格:

<style>

    .table {
      display: table;
      height: 100%;
      margin: 0 auto;
    }
    .table-cell {
      display: table-cell;
      vertical-align: middle;      
    }
    .centered {
      background-color: red;
    }
  </style>

HTML:

<div class="table">
    <div class="table-cell"><div class="centered">centered</div></div>
</div>

演示:

看看这个演示。

如果你正在研究新的浏览器(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),那么表格单元格是最流行的方法。