垂直对齐50%的视口

时间:2013-08-29 19:10:19

标签: javascript jquery css

无论文档有多长,我都会尝试垂直对齐视口的div50%

您可以在此处查看示例http://fancyapps.com/fancybox/#examples

2 个答案:

答案 0 :(得分:2)

可以使用Box偏移属性来获得此效果。

  

此属性指定绝对定位的框顶部的距离   边缘边缘偏移到包含框的顶边下方   块。

来源:http://www.w3.org/TR/CSS2/visuren.html#position-props


jsfiddle

CSS

#centered {
    position: fixed;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    margin: auto;
    height: 200px; /* arbitrary */
    width: 600px; /* arbitrary */
    background-color: grey;
}

答案 1 :(得分:0)

这是一个jQuery示例,无论其高度和宽度如何都将以div为中心。

DEMO http://jsfiddle.net/kevinPHPkevin/dzSPN/120/

function animateHight(newHeight){
    $('div#centered').animate({'height': newHeight, 'margin-top': -newHeight/2}, 600, function(){animateWidth(100);animateHight(100);});
}
function animateWidth(newWidth){
    $('div#centered').animate({'width': newWidth, 'margin-left': -newWidth/2}, 600);
}