zoukankan      html  css  js  c++  java
  • 盒子居中示例

    代码效果:

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

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

    效果图

  • 相关阅读:
    自我介绍
    企业级应用与互联网应用差异
    Java EE 目标
    自我评价
    第二周———搜查令
    软件工程项目____搜查令
    结对项目--黄金点游戏(邓乐&曾亮)
    wordcount程序
    四则运算 来自 http://www.cnblogs.com/ys1101/p/4368103.html
    问题
  • 原文地址:https://www.cnblogs.com/shihaiying/p/13275991.html
Copyright © 2011-2022 走看看