使用css居中盒子的三种方式

151 阅读1分钟

1.父相子绝定位居中: 创建父盒子包裹子盒子的结构并设置宽高背景色

    <style>
        .one {
            width: 600px;
            height: 600px;
            background-color: rgb(135, 209, 246);
        }

        .two {
            width: 200px;
            height: 200px;
            background-color: rgb(133, 242, 217);
        }
    </style>
</head>

<body>
    <div class="one">
        <div class="two"></div>
    </div>
</body>

给one盒子加上相对定位,给子盒子加上绝对定位.同时使其距离父盒子上,左各50%的距离

    <style>
        .one {
            position: relative;
            width: 600px;
            height: 600px;
            background-color: rgb(135, 209, 246);
        }

        .two {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 200px;
            height: 200px;
            background-color: rgb(133, 242, 217);
        }
    </style>

此时发现并没有真正居中

QQ截图20220514202716.jpg 这是因为子盒子自身的宽高也占了移动的距离,此时只要反方向移动盒子宽高的一半就可以了

        .two {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 200px;
            height: 200px;
            background-color: rgb(133, 242, 217);
            transform: translate(-50%, -50%);
        }

大功告成!

QQ截图20220514203323.jpg 2.父相子绝自适应 如上设置父相子绝定位,同时上下左右距离设置为0,外边距设置为自适应

    <style>
        .one {
            position: relative;
            width: 600px;
            height: 600px;
            background-color: rgb(135, 209, 246);
        }

        .two {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            /*外边距设置为自适应*/
            margin: auto;
            width: 200px;
            height: 200px;
            background-color: rgb(133, 242, 217);
        }
    </style>
</head>

<body>
    <div class="one">
        <div class="two"></div>
    </div>

3.flex布局居中 这是我个人比较喜欢的一种居中方式,首先将父盒子转换成弹性容器.然后将主轴与次轴对齐方式设置为居中对齐

    <style>
        .one {
            width: 600px;
            height: 600px;
            background-color: rgb(135, 209, 246);
            /*将父盒子转换成弹性容器*/
            display: flex;
            /*主轴对齐方式为居中对齐*/
            justify-content: center;
            /*次轴对齐方式为居中对齐*/
            align-items: center;
        }

        .two {
            width: 200px;
            height: 200px;
            background-color: rgb(133, 242, 217);
        }
    </style>
</head>

<body>

一步到位!