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

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


当前回答

我认为有两种方法使div中心对齐通过CSS。

.middleDiv {
    position : absolute;    
    width    : 200px;
    height   : 200px;
    left     : 50%;
    top      : 50%;
    margin-left : -100px; /* half of the width  */
    margin-top  : -100px; /* half of the height */
}

这是最简单最好的方法。演示请访问以下链接:

http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html

其他回答

我认为有两种方法使div中心对齐通过CSS。

.middleDiv {
    position : absolute;    
    width    : 200px;
    height   : 200px;
    left     : 50%;
    top      : 50%;
    margin-left : -100px; /* half of the width  */
    margin-top  : -100px; /* half of the height */
}

这是最简单最好的方法。演示请访问以下链接:

http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html

解决方案

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

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

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

实际上有一个解决方案,使用css3,它可以垂直居中一个未知高度的div。诀窍是将div向下移动50%,然后使用transformmy将其移回中间。唯一的前提条件是要居中的元素有一个父元素。例子:

<div class="parent">
    <div class="center-me">
        Text, images, whatever suits you.
    </div>
</div>

.parent { 
    /* height can be whatever you want, also auto if you want a child 
       div to be responsible for the sizing */ 
    height: 200px;
}

.center-me { 
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    /* prefixes needed for cross-browser support */
    -ms-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

所有主流浏览器和ie9及以上版本都支持(别担心ie8,因为它在今年秋天和winxp一起死了。感谢上帝)。

JS小提琴演示

我知道我迟到了,但是这里有一种方法可以将一个维度未知的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>

演示:

看看这个演示。