盒子居中示例

代码效果:

窗口扩大、缩小,滚动条上下、左右移动,盒子都居中显示

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            width: 3000px;
            height: 3000px;
        }

        #box {
            width: 200px;
            height: 200px;
            background: forestgreen;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        var box = document.getElementById('box');
        function center() {
            var pageWidth = document.documentElement.clientWidth; // 浏览器可视宽
            var pageHeight = document.documentElement.clientHeight; // 浏览器可视高
            // 水平居中
            box.style.left = document.documentElement.scrollLeft + (pageWidth - box.offsetWidth) / 2 + 'px';
            // 垂直居中
            box.style.top = document.documentElement.scrollTop + (pageHeight - box.offsetHeight) / 2 + 'px';
        }
        center();
        // 窗口改变事件
        window.onresize = center;

        // 滚动事件
        window.onscroll = center;
    </script>
</body>

</html>

效果图

原文地址:https://www.cnblogs.com/shihaiying/p/13275991.html