我正在尝试使用 Javascript 将 div 垂直居中。因为文本会发生变化,所以我不能使用固定高度。
我想在没有 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);
任何帮助都会很棒 :)
最佳答案
你已经差不多了,你只需要改变一些东西。首先,getElementById
只接受一个 id 字符串,而不是一个选择器。其次,您需要在样式声明中添加“px”。
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';
这是一个更新的 fiddle :http://jsfiddle.net/EttZQ/1/
关于javascript - 使用 Javascript 垂直居中 div(可变高度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17179077/