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>

    效果图

  • 相关阅读:
    图论
    数学
    P2222 外婆婆~
    P2083 找人
    P1215 [USACO1.4]母亲的牛奶 Mother's Milk
    New Rap
    P2298 Mzc和男家丁的游戏
    P2040 打开所有的灯
    P1135 奇怪的电梯
    UVA10474 Where is the Marble?
  • 原文地址:https://www.cnblogs.com/shihaiying/p/13275991.html
Copyright © 2011-2022 走看看