常见的几种水平垂直居中方法

35 阅读1分钟
1. 定位+负margin
    .box1 {
        width: 200px;
        height: 200px;
        background: pink;
        position: relative;
    }

    .box2 {
        width: 50px;
        height: 50px;
        background: steelblue;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-top: -25px;
        margin-left: -25px;
    }
  • 需要知道子元素宽高
2. 定位+margin auto
    .box1 {
        width: 200px;
        height: 200px;
        background: pink;
        position: relative;
    }

    .box2 {
        width: 50px;
        height: 50px;
        background: steelblue;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }
  • 需要知道子元素宽高
3. 定位+transform
    .box1 {
        width: 200px;
        height: 200px;
        background: pink;
        position: relative;
    }

    .box2 {
        width: 50px;
        height: 50px;
        background: steelblue;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }
  • 不需要知道子元素宽高
4. flex布局
    .box1 {
        width: 200px;
        height: 200px;
        background: pink;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .box2 {
        width: 50px;
        height: 50px;
        background: steelblue;
    }
  • 不需要知道子元素宽高
5. table布局
    .box1 {
        width: 200px;
        height: 200px;
        background: pink;
        display: table;
        padding: 20px
    }

    .box2 {
        width: 50px;
        height: 50px;
        background: steelblue;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
6. grid布局
    .box1 {
        width: 200px;
        height: 200px;
        background: pink;
        display: grid;
    }

    .box2 {
        width: 50px;
        height: 50px;
        background: steelblue;
        align-self: center;
        justify-self: center;
    }