水平垂直居中

205 阅读1分钟

前言

万万没想到啊,这种破题目也被自己遇上,而且还脑子短路,记录一下

怎么做

假设我们的要页面基本的元素是这样的

<div class="center">
    <div class="cell"></div>
</div>

//scss
html,body {
    height: 100%;
}
.center {
    height: 100%;
    width: 100%;
    background: antiquewhite
}
.cell {
    width: 200px;
    height: 200px;
    background: black;
}

1. position + transfrom (最常用的了)

.center {
    position: relative;
    .cell {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    } 
}

2. flex + align-items + justify-content (第二常用)

.center {
    display: flex;
    align-items: center;
    justify-content: center;
}

3. grid 布局

.center {
    display: grid;
    align-items:center;
    justify-content: center;
}

4. flex + margin:auto

.center {
    display: flex;
   .cell {
       margin: auto;
   }
}

5. position + margin

.center {
    position: relative;
    .cell {
        position: absolute;
        margin: auto;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }
}

6. display : table-cell

.center {
    width: 500px;   //不可以为100%
    height: 500px;  //不可以为100%
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    .cell {
        display: inline-block;
    }
}

总结

  1. 得多去留意项目里面用到的方法;
  2. 随着前端的发展,会越来越多垂直水平居中的方法,得多留意;