关于页面布局中,如何让一个div水平和垂直居中的五个方案

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    html,body{
        height: 100%;
        overflow: hidden;
       }
    #box{
        border: 1px solid;
        background-color: antiquewhite;
        width: 150px;
        height: 50px;
        text-align: center;
        line-height: 50px;
    }
/* 第一种:定位 */
/* 子绝父相,需要知道盒子的大小 
   将盒子的左上角居中 
   再将盒子向左上移动宽和高的一半 */

/* body{
    position: relative;
}
#box{
   position:absolute;
    top: 50%;
    left: 50%;  
    margin-top: -25px;
    margin-left: -75px;
} */




/* 第二种:定位 */ /* 子绝父相,不需要知道宽高,但是盒子必须有宽高 */ /* body{ position: relative; } #box{ position:absolute; top: 0; right: 0; left: 0; bottom: 0; margin: auto; } */


/* 第三种:定位 */ /* 子绝父相,不需要知道宽高,盒子宽高不是必须的,使用CSS3新特性移动盒子,但是兼容性差 */ /* body{ position: relative; } #box{ position:absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } */



/* 第四种使用弹性布局 ,主轴X轴居中,Y轴也居中.移动端经常用,但是也有兼容性问题*/ /* body{ display: flex; justify-content: center; align-items: center ; } #box{ } */ </style> <body> <div id="box"> chengjunfeng </div> </body> <script> // 第五种,使用js方案 // let Html=document.documentElement, // WinX=Html.clientWidth, // WinY=Html.clientHeight, // boxX=box.offsetWidth, // boxY=box.offsetHeight; //涨见识了,原来id可以直接用,box // Html.style.position="relative"; // box.style.position="absolute"; // box.style.top=(WinY-boxY)/2+'px'; // box.style.left=(WinX-boxX)/2+'px'; </script> </html>

猜你喜欢

转载自www.cnblogs.com/LBJN/p/13364787.html