I'm trying to vertically center a div with Javascript. Because the text is going to be changing, I cannot use a fixed height.
I'd like to do this without Jquery.
#box2 {
width: 100%;
height: 100%;
position:relative;
background-color: orange;
}
#informationBox {
padding: 0.5em;
background-color: #fff;
border-radius: 12pt;
border: solid black 3pt;
max-width: 683px;
margin: 0 auto;
text-align: center;
}
Javascript:
var container = document.getElementById("#box2");
var inner = document.getElementById("#informationBox");
var inHeight = inner.offsetHeight;
container.style.height=(window.innerHeight);
container.style.width=window.innerWidth;
var conHeight=container.offsetHeight;
inner.style.marginTop=((conHeight-inHeight)/2);
Any help would be great :)
http://jsfiddle.net/tmyie/EttZQ/
You pretty much have it, you just need to change a couple things. First, getElementById takes just an id-string, not a selector. Secondly, you need to add 'px' to your style declration.
var container = document.getElementById("box2");
var inner = document.getElementById("informationBox");
var inHeight = inner.offsetHeight;
container.style.height = window.innerHeight;
container.style.width = window.innerWidth;
var conHeight = container.offsetHeight;
inner.style.marginTop = ((conHeight-inHeight)/2)+'px';
Here's an updated fiddle: http://jsfiddle.net/EttZQ/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With