<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
这是最好的代码,以中心的div机器人水平和垂直
div { 位置:绝对的; 上图:50%; 左:50%; 变换:翻译(-50%,-50%); }
其他回答
下面是我之前写的一个脚本(它是用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();
};
这里还有一个方法(防弹),利用“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/
这个解决方案对我很有效
.middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
(或高度:70% /底部:15%
高度:40% /底部:30%…)
我认为有两种方法使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