繁体   English   中英

使用Javascript(可变高度)垂直居中div

[英]Vertically center div with Javascript (variable height)

我正试图用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);

任何帮助都会很棒:)

http://jsfiddle.net/tmyie/EttZQ/

你几乎拥有它,你只需要改变几件事。 首先, getElementById只接受一个id-string,而不是一个选择器。 其次,您需要在样式分离中添加“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';

这是一个更新的小提琴: http//jsfiddle.net/EttZQ/1/

使用具有line-height属性的js。

更少的JavaScript和精确的居中。

box / info可以有min / max-width / height&%或px ...

也调整窗口大小。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>center</title>
<style>
html,body{
 width:100%;
 height:100%;
 margin:0;
 padding:0;
}
#box{
 width:100%;
 height:100%;
 text-align:center;
}
#info{
 display:inline-block;
 margin:0;padding:0 16px;
 line-height:24px;
 border-radius: 12pt;
 border: solid black 3pt;
 text-align: center;
 vertical-align:middle;
 box-sizing: border-box;
}
</style>
<script>
var center=function(){
 var b=document.getElementById('box');
 b.style['line-height']=b.offsetHeight+'px';
}
window.onload=center;
window.onresize=center;
</script>
</head>
<body>
<div id="box"><div id="info">center me pls<br>test</div></div>
</body>
</html>

一个简单的CSS解决方案

http://jsfiddle.net/antouank/EttZQ/2/

body {
    margin: 0;
}
#box2 {
    width: 100%;
    height: 100%;
    position:absolute;
    background-color: orange;
}
#informationBox {
    padding: 0.5em;
    background-color: #fff;
    border-radius: 12pt;
    border: solid black 3pt;
    max-width: 100px;
    margin: 0 auto;
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
}

您只需计算元素的宽度/高度,并将50%更改为您需要居中的任何值。

使容器pos不是静态的。 盒子:pos绝对。 顶部:50%当框高度改变时,将框顶部设置为-1 *高度/ 2。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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