怎么让div在页面居中

    div
    {
        background: blue;
        border:red;
        width:400px; 
        height: 400px;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-top:-200px;
        margin-left: -200px;
    }
    body
    {
        position: relative;
     
    }
    .clearfix::after
    {
        display:block ;
        content: "";
        clear: both;
        
    }
</style>
<body class="clearfix">
    <div>

    </div>
  
</body>

即使我用了clearfix解决高度坍塌 body依然高度为0

body
{
position: absolute;
width:100%;
height:100%;
}


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>display detail</title>
    <style>
        html,body {
            width: 100%;
            height: 100%;
            display: flex;
        
            justify-content: center;
            align-items: center;
        }

        .div1 {
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: rgb(180, 27, 27);
        }


    </style>
</head>
<body>

        <div class="div1">
         div1   
        </div>

  
</body>
</html>
<style>
  .main{
    width:100%;
    height:100%;
    background:skyblue;
    display:flex;   /* 开启flex布局*/
    justify-content: center; /*左右方向设置居中 */
    align-items: center;   /* 垂直方向设置居中*/
  }
  .moudel{
    width:200px;
    height:200px;
    background-color:#ef7474;
    line-height:200px; /* 行高和div高度一致,让文字垂直居中 */
    text-align:center; /* 文本水平居中 */
  }
</style>
<body >
    <div class="main">
      <div class="moudel">
        我要上下左右居中
      </div>
    </div>
</body>

img

核心代码

html,body{
  height: 100%;
  width: 100%;
  padding:0;
  margin: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>
        html,body{
            height: 100%;
            width: 100%;
            padding:0;
            margin:0;
        }
        div {
            background: blue;
            border: red;
            width: 400px;
            height: 400px;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-top: -200px;
            margin-left: -200px;
        }
        .clearfix::after {
            display: block;
            content: "";
            clear: both;
        }
    </style>
</head>
<body class="clearfix">
    <div>
        div
    </div>
</body>
</html>

position:absolute;
lef:0;
right:0;
top:0;
bottom:0;
margin:auto

居中方法有很多,常用的:
1.设置absolute,上下左右均设为0,margin:auto
2.设置absolute, left:50%; top:50%; transform:translate(–50%,-50%)
3.父元素设置display:flex; justify–content:center; align-item:center
4.父元素设置text–align:center; line–height:自身高度

以上是比较简单的四种方法
如有帮助,望采纳^O^谢谢