欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用盒模型让元素在浏览器中垂直水平居中,改变浏览器窗口大小依然居中

程序员文章站 2022-05-01 23:27:38
...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .box{
        display: flex;
        justify-content: center;
        align-items: center;
    }
    div{
        height: 32px;
        border: 1px solid red;
        font-size: 14px;
        line-height: 32px;
    }

</style>
<body class="box">
<div>
   垂直居中
</div>
</body>
</html>

<script>
    window.onload=function (ev) {
        var box = document.getElementsByClassName('box')[0]
        var height = window.innerHeight
        
        box.style.height = height+'px'

        window.onresize = function (ev2) {
          box.style.height = height+'px'
        }
    }
</script>

相关标签: 元素居中