垂直居中div

时间:2011-08-17 10:43:00

标签: javascript css margins

我必须垂直居中,只有上下边距。

所以我用JavaScript生成了边距,就像这样。

var xLength = ((document.getElementById("outerdiv").offsetHeight)+"px");

xLength = (xLength - 222); //222 is the Length of the to be centered div

xMargin = (xLength / 2); //because of the 2 margins
xMargin = (xMargin());

document.getElementById(innerdiv).style.marginTop = xMargin;
document.getElementById(innerdiv).style.marginBottom = xMargin;

请帮忙,不能让它上班,有什么想法吗?

这是外部和内部div的CSS:

#outerdiv {   
    min-height:302px;
    width:58px;
    margin-left:640px;
    z-index:2;
    float:right;
    margin-right:228px;
    border: 1px solid black;
    position:absolute;
}

#innerdiv {
    height:222px;
    width:58px;
    position:absolute;
    border: 1px solid green;
}

HTML:

<div id='outerdiv'>
  <div id='innerdiv'>
  </div>
</div>

2 个答案:

答案 0 :(得分:3)

这是因为元素的父元素本身没有定义的高度。


对于你的JavaScript,一个问题是这一行,根本就没有意义,应该被删除:

xMargin = (xMargin());

您还应该为您设置的值添加“px”,并在ID周围加上引号,如下所示:

document.getElementById('innerdiv').style.marginTop = xMargin + 'px';
document.getElementById('innerdiv').style.marginBottom = xMargin + 'px';

答案 1 :(得分:2)

window.onload = checkAvailableHeight;

window.onresize = checkAvailableHeight;

function checkAvailableHeight(){
    var yourDiv = document.getElementById("yourDiv");
    yourDiv.style.marginTop = ((window.innerHeight - yourDivHeight) / 2) + "px";
}