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

<!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>

猜你喜欢

转载自blog.csdn.net/tcf_jingfeng/article/details/80181791