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

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


当前回答

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

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

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

其他回答

如果你正在使用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/

如果你知道div的定义大小,你可以使用calc。

实例:https://jsfiddle.net/o8416eq3/

注意:只有当你在CSS中硬编码了' ' div '的宽度和高度时,这才有效。

目标# { 位置:固定; 顶部:calc(50vh - 100px/2); 左:calc(50vw - 200px/2); 宽度:200 px; 身高:100 px; 背景颜色:红色; } < div id = '目标' > < / div >

另一个答案是这样的。

<div id="container"> 
    <div id="centered"> </div>
</div>

还有css:

#container {
    height: 400px;
    width: 400px;
    background-color: lightblue;
    text-align: center;
}

#container:before {
    height: 100%;
    content: '';
    display: inline-block;
    vertical-align: middle;
}

#centered {
    width: 100px;
    height: 100px;
    background-color: blue;
    display: inline-block;
    vertical-align: middle;
    margin: 0 auto;
}

尽管当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: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;
}