盒子居中显示

第一种方法:

        <style>    
            #box{
                width: 200px;
                height: 200px;
                background: #ccc;
                border: 10px solid #f00;
                position: absolute;
                left:0;
                top: 0;
                bottom: 0;
                right: 0;
                margin: auto;
            }    
        </style>

 

第二种方法:

        <style>    
            #box{
                width: 200px;
                height: 200px;
                background: #ccc;
                border: 10px solid #f00;
                position: absolute;
            }    
        </style>
        <script>
            window.onload=function(){
                var box=document.getElementById("box"); 
                var l=(document.documentElement.clientWidth-box.offsetWidth)/2;    //可视区的宽度-元素的宽度
                var t=(document.documentElement.clientHeight-box.offsetHeight)/2;
                box.style.left=l+"px";
                box.style.top=t+"px";
            }        
        </script>

 

 

posted @ 2018-08-20 15:54  只是那些  阅读(135)  评论(0编辑  收藏  举报