首页 > 其他 > 详细

盒子居中示例

时间:2020-07-09 21:14:26      阅读:60      评论:0      收藏:0      [点我收藏+]

代码效果:

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!