css实现盒子水平居中对齐

一、flex布局实现水平垂直居中

    给父容器设置(不需要知道宽高) .father{ display: flex; justify-content: center; align-items: center; } 父元素开启弹性布局,子元素外边距设置为auto 原理是利用外边距自动填充实现居中 .father{ display: flex; } .son{ margin: auto; }

二、grid布局实现水平垂直居中

    父元素开启grid布局,子元素外边距设置为auto .father{ display: grid; } .son{ margin: auto; } 父元素开启grid布局,子元素主轴、侧轴都设置居中对齐 .father{ display: grid; } .son{ /* 水平居中 */ justify-self: center; /* 垂直居中 */ align-self: center; }

三、定位实现

    子元素参照父元素进行定位 .father{ position: relative; } .son{ position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; } 定位配合变形位移实现(不需要知道宽高) .father{ position: relative; } .son{ position: absolute; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); }

四、表格布局实现

    给父元素设置表格布局,设置水平垂直方向居中 .father{ display: table-cell; vertical-align: middle; /* text-align属性只对内敛元素有效 */ text-align: center; } .son{ display: inline-block; }

五、文本水平垂直居中

.son{
          
   
            text-align: center;
            line-height: 150px;
        }

相关代码

<style>
        .div1{
            
     
            width: 300px;
            height: 400px;
            border: 2px #f00 solid;

        }
        .div2{
            
     
            width: 150px;
            height: 150px;background-color: rgb(100, 234, 43);
        }
        /* 方法1 */
        /* .father{
            display: flex;
            justify-content: center;
            align-items: center;
        } */

        /* 方法2 */
        /* .father{
            display: flex;
        }
        .son{
            margin: auto;
        } */

        /* 方法3 */
        /* .father{
            display: grid;
        }
        .son{
            margin: auto;
        } */

        /* 方法4 */
        /* .father{
            display: grid;
        }
        .son{
            justify-self: center;
            align-self: center;
        } */

        /* 方法5 */
        /* .father{
            position: relative;
        }
        .son{
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        } */

        /* 方法6 */
        /* .father{
            position: relative;
        }
        .son{
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translateX(-50%) translateY(-50%);
        } */

        /* 方法7 */
        /* .father{
            display: table-cell;
            vertical-align: middle;
              text-align属性只对内敛元素有效 
            text-align: center;
        }
        .son{
            display: inline-block;
        } */

        /* 方法8对文本设置水平垂直居中 */
        .son{
            
     
            text-align: center;
            line-height: 150px;
        }
    </style>
</head>
<body>
    <div class="div1 father">
        <div class="div2 son">一段文字</div>
    </div>
</body>
经验分享 程序员 微信小程序 职场和发展