<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

其他回答

虽然我太晚了,但这很简单。页面中心总是向左50%,顶部50%。减去div width和height的50%设置左右边距。希望它适用于所有地方

身体{ 背景:# EEE; } .center-div { 位置:绝对的; 宽度:200 px; 高度:60 px; 左:50%; margin-left: -100 px; 上图:50%; margin-top: -30 px; 背景:# CCC; 颜色:# 000; text-align:中心; } < div class = " center-div”> <h3>这是中心div</h3> < / div >

div { 位置:绝对的; 上图:50%; 左:50%; 转换:翻译(-50%,-50%); -ms-transform: -50%, -50%;/*即9 */ -webkit-transform (-50%, -50%);/* Chrome, Safari, Opera */ } <身体> <div> div要垂直对齐 < /身体>

位置:主体文档中的绝对div

有位置的元素:绝对的;相对于最近的定位祖先(而不是相对于视口(主体标记),像固定的那样)定位。

然而;如果绝对定位元素没有定位父元素,它将使用文档主体,并随着页面滚动而移动。

来源:CSS位置

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

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

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

下面是我之前写的一个脚本(它是用jQuery库写的):

var centerIt = function (el /* (jQuery element) Element to center */) {
    if (!el) {
        return;
    }
    var moveIt = function () {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
    }; 
    $(window).resize(moveIt);
    moveIt();
};

实际上有一个解决方案,使用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小提琴演示