前端

89 阅读1分钟

手写垂直水平居中

  1. 第一种方法: position+margin负值的方法(宽高固定)
/* position+margin负值的方法(宽高固定) */
    .box {
        position: relative; /*子级定位参照物*/
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }
    .item {
        position: absolute; /*根据父级去定位*/
        left: 50%;
        top: 50%;
        margin-top: -150px;  /* 高度的一半 */
        margin-left: -100px; /*宽度的一半*/
        width: 200px;
        height: 300px;
        background-color: pink;
    }
  1. 第二种方法:position+margin:auto (固定宽高)
.box {
        width: 500px;
        height: 500px;
        border: 5px solid red;
        position: relative;
    }
    .item {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        width: 200px;
        height: 200px;
        background-color: pink;
    }
  1. display:table-cell + vertical-align:middle (固定宽度)
.box {
        /* display:table-cell指让标签元素以表格单元格的形式呈现 */
        display: table-cell;
        /* 居中对齐 */
        vertical-align: middle;
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }
    .item {
        margin: auto;
        width: 200px;
        height: 200px;
        background-color: pink;
    }
  1. position+transform(不需要固定宽高)
.box {
        position: relative;
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }
    .item {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        width: 200px;
        height: 200px;
        background-color: pink;
    }
  1. flex (不需要固定宽高)
.box {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 500px;
        height: 500px;
        border: 5px solid red;
    }
    .item {
        width: 200px;
        height: 200px;
        background-color: pink;
    }