CSS盒子水平垂直居中的实现

176 阅读1分钟

一. 前言

在实际开发中我们经常会遇到盒子需要水平垂直居中的情况,这个时候就需要进行设置.

  • 注 : 个人开发习惯与临场场景不同,下面仅列出我个人常用的两种方式

二.通过定位与平移实现盒子水平垂直居中

此处需要注意父元素要有定位属性,这里演示只有一层盒子,默认父元素为浏览器,已省略

.box {
        width: 200px;
        height: 200px;
        background-color: aqua;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

效果对比:

  • 结构

image.png

  • 效果展示

image.png

三.通过弹性盒子实现盒子水平垂直居中

通过弹性盒子主侧轴属性进行实现

 .fatherBox{
        width: 600px;
        height: 600px;
        border: 1px solid black;
        /*开启弹性盒子*/
        display: flex;
        /* 侧轴居中 */
        align-items: center;  
        /* 主轴两侧靠边中间自适应,此处单个子元素为居中 */
        justify-content: center;
    }
    .box {
        width: 200px;
        height: 200px;
        background-color: aqua;
    }

效果对比:

  • 结构

image.png

  • 效果展示

image.png