将一个<div>
元素在页面上垂直和水平居中的最佳方法?
我知道margin-left: auto; margin-right: auto;
会在水平方向上居中,但在垂直方向上有什么好办法呢?
这个演示中的主要技巧是,在正常的元素流动中,从上到下,所以margin-top: auto
被设置为零。然而,一个绝对定位的元素对于自由空间的分配作用是一样的,同样可以在指定的top
和bottom
处垂直居中(在IE7中不起作用)。
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div></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();
};