简体   繁体   中英

Center a div vertically

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM