Javascript - 使用纯JavaScript中心div水平和垂直

时间:2015-09-02 13:23:58

标签: javascript jquery centering

我试图在不知道高度/宽度的情况下水平和垂直居中。我已经在jquery中实现了它,但我正在努力将其转换为纯粹的js,因为我不想要依赖...任何想法?

<script>
    $(document).ready(mt);
    $(window).resize(mt);
    function mt(){
    var contentLocked = $('.lockerPopup').outerHeight(); 
        marginTop = ( $(document).height() - contentLocked ) / 2;
        $('.lockerPopup').css({'top': marginTop});}
</script>

3 个答案:

答案 0 :(得分:0)

使用.offsetWidth.offsetHeight获取元素的尺寸,使用window.innerWidthwindow.innerHeight获取窗口的尺寸。其余的逻辑非常简单,可以使用.style.top.style.left来集中它。

请参阅http://codepen.io/anon/pen/JYjqWZ

或者,如果您想要将多个内容置于中心或者您不需要将其置于绝对位置,我建议您查看flexbox或使用

top: 50%;
left: 50%;
transform: translate(-50%, -50%);
在你的CSS中

完全远离JS。

答案 1 :(得分:0)

你可以使用左50%居中;前50%和-webkit-transform:translate(-50%,50%); (显然添加了所有其他版本的webkit转换以实现跨浏览器兼容性。

无论宽度/高度和父容器大小如何,这都会使div居中。

答案 2 :(得分:0)

你不需要javascript, 你只能使用CSS:http://jsfiddle.net/leojavier/gjah19y7/

<div class="container">
    <div class="element"><p>test</p></div>
</div>

CSS

html,body{
    height:100%;
    width:100%;
}
.container {
    display:table;
    height:100%;
    width:100%;
    background:#CCC;
}

.element {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
    width:100px;
    height:100px;
    color:#222;
}