盒子水平垂直居中


盒子水平垂直居中

这篇总结主要讲解了盒子水平垂直居中的几种方法?

方法1:子绝父相+margin:left/top; 固定宽高的盒子居中

方法2:子绝父相+transfrom

方法3:子绝父相(子盒子上下左右都赋值为0)+margin:auto;

方法4:flex布局,给父盒子添加flex布局,同时在弹性容器(父盒子)内设置主轴居中,侧轴居中

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,
     initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        /* 方法1 
        .father {
            position: relative;
            margin: 0 auto;
            width: 200px;
            height: 200px;
            background-color: pink;
        }
        .son {
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -50px;
            margin-top: -50px;
            width: 100px;
            height: 100px;
            background-color: black;
        } */
 
        /* 方法2
        .father {
            position: relative;
            margin: 0 auto;
            width: 200px;
            height: 200px;
            background-color: pink;
        }
        .son {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            width: 100px;
            height: 100px;
            background-color: black;
        }  */
        /* 方法3
        .father {
            position: relative;
            margin: 0 auto;
            width: 200px;
            height: 200px;
            background-color: pink;
        }
        .son {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            width: 100px;
            height: 100px;
            background-color: black;
        } */
        /* 方法4 */
        .father {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto;
            width: 200px;
            height: 200px;
            background-color: pink;
        }
        .son {
            width: 100px;
            height: 100px;
            background-color: black;
        }
    </style>
</head>
<body>
    <!-- 需求:请你写出父子关系盒子居中4种方法 -->
    <!-- 提示: 定位+margin  
    定位+transfrom  定位+方位名词0  flex布局 -->
    <div class="father">
        <div class="son"></div>
    </div>
</body>
</html>

文章作者: 冷杨威
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 冷杨威 !
  目录
-->