开发者

Center a div vertically

开发者 https://www.devze.com 2023-03-29 04:24 出处:网络
I have to center a div vertically, with only a margin above and below. So I made it generate the margin with JavaScript, like this.

I have to center a div vertically, with only a margin above and below.

So I made it generate the margin with JavaScript, like this.

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;

Please help, can't get it to work, any ideas?

Here is the CSS of outer and inner div:

#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>


This is because your element's parent doesn't have a defined height itself.


With respect to your JavaScript, one problem is this line, which makes no sense at all and should be removed:

xMargin = (xMargin());

You should also add 'px' to the values you are setting, and put quotes around the ID, like this:

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


window.onload = checkAvailableHeight;

window.onresize = checkAvailableHeight;

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

精彩评论

暂无评论...
验证码 换一张
取 消