简体   繁体   English

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

[英]Javascript - Center div horizontal and vertical with pure javascript

I'm trying to center a div horizontally and verticlaly without knowing the height/width. 我正在尝试在不知道高度/宽度的情况下水平和垂直居中div的位置。 I've achieved it within jquery but am struggling to convert it to pure js as I don't want dependancy.. any ideas? 我已经在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>

Use .offsetWidth and .offsetHeight to get the dimensions of your element and window.innerWidth and window.innerHeight for the dimensions of the window. 使用.offsetWidth.offsetHeight获取元素和window.innerWidthwindow.innerHeight的尺寸,以获取窗口的尺寸。 The rest of the logic is pretty straight forward to center it using .style.top and .style.left . 其余的逻辑很简单,可以使用.style.top.style.left

See http://codepen.io/anon/pen/JYjqWZ http://codepen.io/anon/pen/JYjqWZ

Alternatively, if you want to center multiple things or you don't need it to be positioned absolutely, I would suggest looking into flexbox or use 另外,如果您想将多个内容居中或不需要绝对放置flexbox ,我建议您研究flexbox或使用

top: 50%;
left: 50%;
transform: translate(-50%, -50%);

in your CSS to stay away from JS entirely. 在您的CSS中完全远离JS。

you can center by using left 50%; 您可以使用左50%居中; top 50% and -webkit-transform: translate(-50%,50%); 前50%和-webkit-transform:translate(-50%,50%); (obviously add all of the other versions of webkit transform for cross-browser compatibility. (显然,添加了所有其他版本的webkit转换以实现跨浏览器兼容性。

This will always center the div no matter what its width/height and parent container size. 无论div的宽度/高度和父容器的大小如何,它始终将居中。

You don't need javascript for that, you can do it only using CSS: http://jsfiddle.net/leojavier/gjah19y7/ 您不需要使用javascript,只需使用CSS即可: http : //jsfiddle.net/leojavier/gjah19y7/

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

CSS 的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;
}

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

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